<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
<meta property="og:type" content="website">
<meta property="og:title" content="玉丸子 | Blog">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/page/3/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
<meta property="og:locale">
<meta property="article:author" content="玉丸子">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/page/3/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh'
  };
</script>
<title>玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">

    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/30/2017-07-30-JavaClosure/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/30/2017-07-30-JavaClosure/" class="post-title-link" itemprop="url">Java中的闭包之争</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-30 18:00:00" itemprop="dateCreated datePublished" datetime="2017-07-30T18:00:00+08:00">2017-07-30</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <blockquote>
<p>闭包一直都是<code>Java</code>社区中争论不断的话题,很多语言例如<code>JavaScript</code>,<code>Ruby</code>,<code>Python</code>等都支持闭包这个语言特性,闭包功能强大且灵活,<code>Java</code>并没有显式地支持它,但其实<code>Java</code>中也存在着所谓的”闭包”.</p>
</blockquote>
<hr>
<blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/30/2017-07-30-JavaClosure/">https://sylvanassun.github.io/2017/07/30/2017-07-30-JavaClosure/</a></p>
</blockquote>
<h3 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h3><hr>
<p>定义一个闭包的要点如下: </p>
<ul>
<li>一个依赖于外部环境的<code>自由变量</code>的函数.</li>
</ul>
<ul>
<li>这个函数能够访问外部环境的<code>自由变量</code>.</li>
</ul>
<p>也就是说,<strong>外部环境持有内部函数所依赖的<code>自由变量</code>,由此对内部函数形成了闭包.</strong></p>
<h4 id="自由变量"><a href="#自由变量" class="headerlink" title="自由变量"></a>自由变量</h4><hr>
<p>那么什么是<code>自由变量</code>呢?<strong><code>自由变量</code>就是在函数自身作用域之外的变量</strong>,一个函数$f(x) = x + y$,其中<code>y</code>就是<code>自由变量</code>,它并不是这个函数自身的自变量,而是通过外部环境提供的.</p>
<p>下面以<code>JavaScript</code>的一个闭包为例: </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Add</span>(<span class="params">y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> x + y;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对于内部函数<code>function(x)</code>来说,<code>y</code>就是<code>自由变量</code>.而<code>y</code>是函数<code>Add(y)</code>内的参数,所以<code>Add(y)</code>对内部函数<code>function(x)</code>形成了一个闭包.</p>
<p>这个闭包将<code>自由变量y</code>与内部函数绑定在了一起,也就是说,当<code>Add(y)</code>函数执行完毕后,它不会随着函数调用结束后被回收(不能在栈上分配空间).</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> add_function = Add(<span class="number">5</span>); <span class="comment">// 这时y=5,并且与返回的内部函数绑定在了一起</span></span><br><span class="line"><span class="keyword">var</span> result = add_function(<span class="number">10</span>); <span class="comment">// x=10,返回最终的结果 10 + 5 = 15</span></span><br></pre></td></tr></table></figure>

<h3 id="Java中的闭包"><a href="#Java中的闭包" class="headerlink" title="Java中的闭包"></a>Java中的闭包</h3><hr>
<p><code>Java</code>与<code>JavaScript</code>又或者其他支持闭包的语言不同,它是一个基于类的面向对象语言,也就是说<strong>一个方法所用到的<code>自由变量</code>永远都来自于其所在类的实例的.</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AddUtils</span> </span>&#123;  </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> y = <span class="number">5</span>;  </span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">    	retrun x + y;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样一个方法<code>add(x)</code>拥有一个参数<code>x</code>与一个<code>自由变量y</code>,它的返回值也依赖于这个<code>自由变量y</code>.<code>add(x)</code>想要正常工作的话,就必须依赖于<code>AddUtils</code>类的一个实例,不然它无法知道<code>自由变量y</code>的值是多少,也就是<code>自由变量</code>未与<code>add(x)</code>进行绑定.</p>
<p>严格上来说,<code>add(x)</code>中的<code>自由变量</code>应该为<code>this</code>,这是因为<code>y</code>也是通过<code>this</code>关键字来访问的.</p>
<p>所以说,在<code>Java</code>中闭包其实无处不在,只不过我们难以发现而已.但面向对象的语言一般都不把类叫成闭包,这是一种习惯.</p>
<p><code>Java</code>中的内部类就是一种典型的闭包结构.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Outer</span> </span>&#123;</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> y = <span class="number">5</span>;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Inner</span> </span>&#123;</span><br><span class="line">		<span class="keyword">private</span> <span class="keyword">int</span> x = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line">		<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">()</span> </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> x + y;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure>
<p>内部类通过一个指向外部类的引用来访问外部环境中的<code>自由变量</code>,由此形成了一个闭包.</p>
<h3 id="匿名内部类"><a href="#匿名内部类" class="headerlink" title="匿名内部类"></a>匿名内部类</h3><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> interface <span class="title">AnonInner</span><span class="params">()</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">int</span> <span class="title">add</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Outer</span> </span>&#123;</span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">public</span> AnonInner <span class="title">getAnonInner</span><span class="params">(<span class="keyword">final</span> <span class="keyword">int</span> x)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">final</span> <span class="keyword">int</span> y = <span class="number">5</span>;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">new</span> AnonInner() &#123;</span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">()</span> </span>&#123;</span><br><span class="line">				<span class="keyword">return</span> x + y;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>getAnonInner(x)</code>方法返回了一个匿名内部类<code>AnonInner</code>,匿名内部类不能显式地声明构造函数,也不能对构造函数传参,且返回的是一个<code>AnonInner</code>接口,但它的<code>add()</code>方法实现中用到了两个<code>自由变量</code>(<code>x</code>与<code>y</code>),也就是说外部方法<code>getAnonInner(x)</code>对这个匿名内部类构成了闭包.</p>
<p>但我们发现<code>自由变量</code>都被加上了<code>final</code>修饰符,这是因为<code>Java</code>对闭包支持的不完整导致的.</p>
<p>对于<code>自由变量</code>的捕获策略有以下两种: </p>
<ul>
<li>capture-by-value: 只需要在创建闭包的地方把捕获的值拷贝一份到对象里即可.<code>Java</code>的匿名内部类和<code>Java 8</code>新的<code>lambda</code>表达式都是这样实现的.</li>
</ul>
<ul>
<li>capture-by-reference: 把被捕获的局部变量“提升”（hoist）到对象里.<code>C#</code>的匿名函数(匿名委托/lambda表达式)就是这样实现的.</li>
</ul>
<p><code>Java</code>只实现了<code>capture-by-value</code>,但又没有对外说明这一点,为了以后能进一步扩展成支持<code>capture-by-reference</code>留后路,所以干脆就不允许向被捕获的变量赋值,所以这些<code>自由变量</code>需要强制加上<code>final</code>修饰符(在<code>Jdk8</code>中似乎已经没有这种强制限制了).</p>
<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.ibm.com/developerworks/java/library/j-jtp04247/index.html">Java theory and practice: The closures debate</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="http://rednaxelafx.iteye.com/blog/245022">关于对象与闭包的关系的一个有趣小故事</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/27416568/answer/36565794">JVM的规范中允许编程语言语义中创建闭包(closure)吗？ - 知乎</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.zhihu.com/question/28190927/answer/39786939">为什么Java闭包不能通过返回值之外的方式向外传递值？ - 知乎</a></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/27/2017-07-27-Graph_WeightedDigraph/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/27/2017-07-27-Graph_WeightedDigraph/" class="post-title-link" itemprop="url">图的那点事儿(4)-加权有向图</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-27 12:00:00" itemprop="dateCreated datePublished" datetime="2017-07-27T12:00:00+08:00">2017-07-27</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Graph/" itemprop="url" rel="index"><span itemprop="name">Graph</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph</a></p>
</blockquote>
<h3 id="加权有向图"><a href="#加权有向图" class="headerlink" title="加权有向图"></a>加权有向图</h3><hr>
<p><code>有向图</code>的实现比<code>无向图</code>更加简单,要实现<code>加权有向图</code>只需要在上一章讲到的<code>加权无向图</code>的实现修改一下即可.</p>
<h4 id="DirectedEdge"><a href="#DirectedEdge" class="headerlink" title="DirectedEdge"></a>DirectedEdge</h4><hr>
<p>由于<code>有向图</code>的边都是带有方向的,所以下面这个实现提供了<code>from()</code>与<code>to()</code>函数,用于获取代表<code>v-&gt;w</code>的两个<code>顶点</code>.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DirectedEdge</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> v;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> w;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">double</span> weight;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DirectedEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w, <span class="keyword">double</span> weight)</span> </span>&#123;</span><br><span class="line">        validateVertexes(v, w);</span><br><span class="line">        <span class="keyword">if</span> (Double.isNaN(weight)) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Weight &quot;</span> + weight + <span class="string">&quot; is  NaN!&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.v = v;</span><br><span class="line">        <span class="keyword">this</span>.w = w;</span><br><span class="line">        <span class="keyword">this</span>.weight = weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">from</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> v;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">to</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> w;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">weight</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> v + <span class="string">&quot;-&gt;&quot;</span> + w + <span class="string">&quot; &quot;</span> + String.format(<span class="string">&quot;%5.2f&quot;</span>, weight);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertexes</span><span class="params">(<span class="keyword">int</span>... vertexes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertexes.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (vertexes[i] &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertex &quot;</span> + vertexes[i] + <span class="string">&quot; must be positive number!&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="EdgeWeightedDigraph"><a href="#EdgeWeightedDigraph" class="headerlink" title="EdgeWeightedDigraph"></a>EdgeWeightedDigraph</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EdgeWeightedDigraph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String NEWLINE = System.getProperty(<span class="string">&quot;line.separator&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of vertices in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> vertex;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of edges in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> edge;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// adj[v] = adjacency list for vertex v</span></span><br><span class="line">    <span class="keyword">private</span> Bag&lt;DirectedEdge&gt;[] adj;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// indegree[v] = indegree of vertex v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] indegree;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">EdgeWeightedDigraph</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        String message = String.format(<span class="string">&quot;Vertex %d must be positive number!&quot;</span>, vertex);</span><br><span class="line">        validatePositiveNumber(message, vertex);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">        <span class="keyword">this</span>.edge = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.indegree = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.adj = (Bag&lt;DirectedEdge&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            adj[v] = <span class="keyword">new</span> Bag&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">EdgeWeightedDigraph</span><span class="params">(Scanner scanner)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(scanner.nextInt());</span><br><span class="line">        <span class="keyword">int</span> edge = scanner.nextInt();</span><br><span class="line">        String message = String.format(<span class="string">&quot;Edge %d must be positive number!&quot;</span>, edge);</span><br><span class="line">        validatePositiveNumber(message, edge);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edge; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> v = scanner.nextInt();</span><br><span class="line">            <span class="keyword">int</span> w = scanner.nextInt();</span><br><span class="line">            validateVertex(v);</span><br><span class="line">            validateVertex(w);</span><br><span class="line">            <span class="keyword">double</span> weight = scanner.nextDouble();</span><br><span class="line">            addEdge(<span class="keyword">new</span> DirectedEdge(v, w, weight));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> vertex;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> edge;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(DirectedEdge e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> v = e.from();</span><br><span class="line">        <span class="keyword">int</span> w = e.to();</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        adj[v].add(e);</span><br><span class="line">        indegree[w]++;</span><br><span class="line">        edge++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;DirectedEdge&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">outdegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> indegree[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 在有向图中每条边只会出现一次</span></span><br><span class="line">	<span class="comment">// 遍历边集不需要在无向图里那样为了消除重复边而进行复杂的判断</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;DirectedEdge&gt; <span class="title">edges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Bag&lt;DirectedEdge&gt; list = <span class="keyword">new</span> Bag&lt;DirectedEdge&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (DirectedEdge e : adj(v)) &#123;</span><br><span class="line">                list.add(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringBuilder s = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        s.append(vertex + <span class="string">&quot; &quot;</span> + edge + NEWLINE);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            s.append(v + <span class="string">&quot;: &quot;</span>);</span><br><span class="line">            <span class="keyword">for</span> (DirectedEdge e : adj[v]) &#123;</span><br><span class="line">                s.append(e + <span class="string">&quot;  &quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            s.append(NEWLINE);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> s.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validatePositiveNumber</span><span class="params">(String message, <span class="keyword">int</span>... numbers)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numbers.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (numbers[i] &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(message);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>加权有向图</code>的实现与<code>加权无向图</code>区别不大,而且因为<code>有向图</code>中的边只会出现一次,实现代码要比<code>无向图</code>更简单.</p>
<p><a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/tree/master/src/main/java/chapter4_graphs/C4_4_ShortestPaths">本文中的所有完整代码请到我的GitHub中查看</a></p>
<h3 id="最短路径"><a href="#最短路径" class="headerlink" title="最短路径"></a>最短路径</h3><hr>
<p>“找到一个<code>顶点</code>到达另一个<code>顶点</code>之间的<code>最短路径</code>“是<code>图论</code>研究中的经典算法问题.在<code>加权有向图</code>中,每条<code>有向路径</code>都有一个与之对应的<code>路径权重</code>(路径中所有边的<code>权重</code>之和),要找到一条<code>最短路径</code>其实就是找到<code>路径权重</code>最小的那条路径.</p>
<p><img src="http://algs4.cs.princeton.edu/44sp/images/shortest-path.png" alt="加权有向图中的最短路径"></p>
<h4 id="单点最短路径"><a href="#单点最短路径" class="headerlink" title="单点最短路径"></a>单点最短路径</h4><hr>
<p>“从<code>s</code>到目的地<code>v</code>是否存在一条<code>有向路径</code>,如果有,找出最短的那条路径”.类似这样的问题就是<code>单点最短路径</code>问题,它是我们主要研究的问题.</p>
<p><code>单点最短路径</code>的结果是一棵<code>最短路径树</code>,它是<code>图</code>的一幅<code>子图</code>,<strong>包含了从起点到所有可达顶点的<code>最短路径</code>.</strong></p>
<p>从起点到一个顶点可能存在两条长度相等的路径,如果出现这种情况,可以删除其中一条路径的最后一条边,直到从起点到每个顶点都只有一条路径相连.</p>
<h4 id="最短路径的数据结构"><a href="#最短路径的数据结构" class="headerlink" title="最短路径的数据结构"></a>最短路径的数据结构</h4><hr>
<p><img src="http://algs4.cs.princeton.edu/44sp/images/spt.png"></p>
<p>要实现<code>最短路径</code>的算法还需要借助以下数据结构: </p>
<ul>
<li>edgeTo[]: 一个<code>由顶点索引</code>的<code>DirectedEdge</code>对象的父链接数组,其中<code>edgeTo[v]</code>的值为树中连接<code>v</code>和它的父节点的边.</li>
</ul>
<ul>
<li>distTo[]: 一个<code>由顶点索引</code>的<code>double</code>数组,其中<code>distTo[v]</code>代表从<code>起点</code>到<code>v</code>的已知最短路径的长度.</li>
</ul>
<ul>
<li>初始化时,<code>edgeTo[s]</code>的值为<code>null</code>(<code>s</code>为起点),<code>distTo[s]</code>的值为<code>0.0</code>,从<code>s</code>到不可达的顶点距离为<code>Double.POSITIVE_INFINITY</code>.</li>
</ul>
<h4 id="让边松弛"><a href="#让边松弛" class="headerlink" title="让边松弛"></a>让边松弛</h4><hr>
<p><code>最短路径</code>算法都基于<code>松弛(Relaxation)</code>操作,<strong>它在遇到新的边时,通过更新这些信息就可以得到新的最短路径.</strong></p>
<p>假设对边<code>v-&gt;w</code>进行松弛操作,意味着要先检查从<code>s</code>到<code>w</code>的<code>最短路径</code>是否是先从<code>s</code>到<code>v</code>,然后再由<code>v</code>到<code>w</code>(也就是说<code>v-&gt;w</code>是更短的一条路径),如果是,那么就进行更新.由<code>v</code>到达<code>w</code>的<code>最短路径</code>是<code>distTo[v]</code>与<code>e.weight()</code>之和,如果这个值大于<code>distTo[w]</code>,称这条边松弛失败,并将它忽略.</p>
<p>松弛操作就像用一根橡皮筋沿着连续两个<code>顶点</code>的路径紧紧展开,放松一条边就像将这条橡皮筋转移到另一条更短的路径上,从而缓解橡皮筋的压力.</p>
<p><img src="http://algs4.cs.princeton.edu/44sp/images/relaxation-edge.png" alt="松弛操作的两种情况(失败与成功)"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 松弛一条边</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(DirectedEdge e)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> v = e.from(), w = e.to();</span><br><span class="line">	<span class="comment">// 如果s-&gt;v-&gt;w的路径更小则进行更新</span></span><br><span class="line">    <span class="keyword">if</span> (distTo[w] &gt; distTo[v] + e.weight()) &#123;</span><br><span class="line">        distTo[w] = distTo[v] + e.weight();</span><br><span class="line">        edgeTo[w] = e;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 松弛一个顶点的所有邻接边</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(EdgeWeightedDigraph G, <span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (DirectedEdge e : G.adj(v)) &#123;</span><br><span class="line">        <span class="keyword">int</span> w = e.to();</span><br><span class="line">        <span class="keyword">if</span> (distTo[w] &gt; distTo[v] + e.weight()) &#123;</span><br><span class="line">            distTo[w] = distTo[v] + e.weight();</span><br><span class="line">            edgeTo[w] = e;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="Dijkstra算法"><a href="#Dijkstra算法" class="headerlink" title="Dijkstra算法"></a>Dijkstra算法</h3><hr>
<p><code>Dijkstra算法</code>类似于<code>Prim算法</code>,它将<code>distTo[s]</code>初始化为<code>0.0</code>,<code>distTo[]</code>中的其他元素初始化为<code>Double.POSITIVE_INFINITY</code>.然后将<code>distTo[]</code>中最小的<code>非树顶点</code>放松并加入树中,一直重复直到所有的顶点都在树中或者所有的<code>非树顶点</code>的<code>distTo[]</code>值均为<code>Double.POSITIVE_INFINITY</code>.</p>
<p><code>Dijkstra算法</code>与<code>Prim算法</code>都是用添加边的方式构造一棵树:</p>
<ul>
<li><code>Prim算法</code>每次添加的是距离<code>树</code>最近的<code>非树顶点</code>.</li>
</ul>
<ul>
<li><code>Dijkstra算法</code>每次添加的都是<strong>离<code>起点</code>最近的<code>非树顶点</code></strong>.</li>
</ul>
<p>从上述的步骤我们就能看出,<code>Dijkstra算法</code>需要一个优先队列(也可以用<code>斐波那契堆</code>)来保存需要被放松的<code>顶点</code>并确认下一个被放松的<code>顶点</code>(也就是取出最小的).</p>
<p>如此简单的<code>Dijkstra算法</code>也有其缺点,那就是它<strong>只适用于解决<code>权重非负</code>的<code>图</code>.</strong></p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/5/57/Dijkstra_Animation.gif" alt="Dijkstra算法的运行轨迹"></p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/e/e4/DijkstraDemo.gif"></p>
<h4 id="实现代码"><a href="#实现代码" class="headerlink" title="实现代码"></a>实现代码</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DijkstraSP</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// distTo[v] = distance of  shortest s -&gt; v path</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span>[] distTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// edgeTo[v] = last edge on shortest s - &gt; v path</span></span><br><span class="line">    <span class="keyword">private</span> DirectedEdge[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// priority queue of vertices</span></span><br><span class="line">    <span class="keyword">private</span> IndexMinPQ&lt;Double&gt; pq;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DijkstraSP</span><span class="params">(EdgeWeightedDigraph digraph, <span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">        validateNegativeWeight(digraph);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.distTo = <span class="keyword">new</span> <span class="keyword">double</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> DirectedEdge[vertex];</span><br><span class="line"></span><br><span class="line">        validateVertex(s);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            distTo[v] = Double.POSITIVE_INFINITY;</span><br><span class="line">        distTo[s] = <span class="number">0.0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将起点放入索引优先队列,并不断地进行松弛</span></span><br><span class="line">        pq = <span class="keyword">new</span> IndexMinPQ&lt;&gt;(vertex);</span><br><span class="line">        pq.insert(s, distTo[s]);</span><br><span class="line">        <span class="keyword">while</span> (!pq.isEmpty()) &#123;</span><br><span class="line">            <span class="keyword">int</span> v = pq.delMin();</span><br><span class="line">			<span class="comment">// 对权值最小的非树顶点的所有邻接边集进行松弛操作</span></span><br><span class="line">            <span class="keyword">for</span> (DirectedEdge e : digraph.adj(v))</span><br><span class="line">                relax(e);</span><br><span class="line">        &#125;</span><br><span class="line">		</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// relax edge e and update pq if changed</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(DirectedEdge e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> v = e.from(), w = e.to();</span><br><span class="line">		<span class="comment">// s -&gt; v -&gt; w的权重</span></span><br><span class="line">        <span class="keyword">double</span> weight = distTo[v] + e.weight();</span><br><span class="line">        <span class="keyword">if</span> (distTo[w] &gt; weight) &#123;</span><br><span class="line">            distTo[w] = weight;</span><br><span class="line">            edgeTo[w] = e;</span><br><span class="line">            <span class="keyword">if</span> (pq.contains(w))</span><br><span class="line">                pq.decreaseKey(w, weight);</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                pq.insert(w, weight);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateNegativeWeight</span><span class="params">(EdgeWeightedDigraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (DirectedEdge e : digraph.edges()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (e.weight() &lt; <span class="number">0</span>)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Edge &quot;</span> + e + <span class="string">&quot; has negative weight.&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">distTo</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> distTo[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasPathTo</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> distTo[v] &lt; Double.POSITIVE_INFINITY;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;DirectedEdge&gt; <span class="title">pathTo</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">if</span> (!hasPathTo(v)) <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        Stack&lt;DirectedEdge&gt; path = <span class="keyword">new</span> Stack&lt;DirectedEdge&gt;();</span><br><span class="line">        <span class="keyword">for</span> (DirectedEdge e = edgeTo[v]; e != <span class="keyword">null</span>; e = edgeTo[e.from()]) &#123;</span><br><span class="line">            path.push(e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> path;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = distTo.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述的代码也可以用于处理<code>加权无向图</code>,但需要修改传入的对象类型.不管是<code>无向图</code>还是<code>有向图</code>它们对于<code>最短路径</code>问题是等价的.</p>
<h3 id="无环加权有向图中的最短路径算法"><a href="#无环加权有向图中的最短路径算法" class="headerlink" title="无环加权有向图中的最短路径算法"></a>无环加权有向图中的最短路径算法</h3><hr>
<p>如果是处理<code>无环图</code>的情况下,还会有一种比<code>Dijkstra算法</code>更快、更简单的算法.它的特点如下:</p>
<ul>
<li>能够处理<code>负权重</code>的边.</li>
</ul>
<ul>
<li><p>能够在线性时间内解决单点最短路径问题.</p>
</li>
<li><p>在已知是一张<code>无环图</code>的情况下,它是找出<code>最短路径</code>效率最高的方法.</p>
</li>
<li><p>实现比<code>Dijkstra算法</code>更简单.</p>
</li>
</ul>
<p>只需要将所有<code>顶点</code><strong>按照<code>拓扑排序</code>的顺序</strong>来<code>松弛边</code>,就可以得到这个简单高效的算法.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AcyclicSP</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// distTo[v] = distance  of shortest s-&gt;v path</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span>[] distTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// edgeTo[v] = last edge on shortest s-&gt;v path</span></span><br><span class="line">    <span class="keyword">private</span> DirectedEdge[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">AcyclicSP</span><span class="params">(EdgeWeightedDigraph digraph, <span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line">        distTo = <span class="keyword">new</span> <span class="keyword">double</span>[vertex];</span><br><span class="line">        edgeTo = <span class="keyword">new</span> DirectedEdge[vertex];</span><br><span class="line"></span><br><span class="line">        validateVertex(s);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            distTo[v] = Double.POSITIVE_INFINITY;</span><br><span class="line">        distTo[s] = <span class="number">0.0</span>;</span><br><span class="line"></span><br><span class="line">        </span><br><span class="line">        Topological topological = <span class="keyword">new</span> Topological(digraph);</span><br><span class="line">        <span class="keyword">if</span> (!topological.hasOrder())</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Digraph is not acyclic.&quot;</span>);</span><br><span class="line">		<span class="comment">// 按照拓扑排序的顺序进行放松操作</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : topological.order()) &#123;</span><br><span class="line">            <span class="keyword">for</span> (DirectedEdge e : digraph.adj(v))</span><br><span class="line">                relax(e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(DirectedEdge e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> v = e.from(), w = e.to();</span><br><span class="line">        <span class="keyword">double</span> weight = distTo[v] + e.weight();</span><br><span class="line">        <span class="keyword">if</span> (distTo[w] &gt; weight) &#123;</span><br><span class="line">            distTo[w] = weight;</span><br><span class="line">            edgeTo[w] = e;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="最长路径"><a href="#最长路径" class="headerlink" title="最长路径"></a>最长路径</h4><hr>
<p>要想找出一条<code>最长路径</code>,只需要把<code>distTo[]</code>的初始化变为<code>Double.NEGATIVE_INFINITY</code>,并更改<code>relax()</code>函数中的不等式的方向.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">AcyclicLP</span><span class="params">(EdgeWeightedDigraph G, <span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">      distTo = <span class="keyword">new</span> <span class="keyword">double</span>[G.vertex()];</span><br><span class="line">      edgeTo = <span class="keyword">new</span> DirectedEdge[G.vertex()];</span><br><span class="line"></span><br><span class="line">      validateVertex(s);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 全部初始化为负无穷</span></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; G.vertex(); v++)</span><br><span class="line">          distTo[v] = Double.NEGATIVE_INFINITY;</span><br><span class="line">      distTo[s] = <span class="number">0.0</span>;</span><br><span class="line"></span><br><span class="line">      Topological topological = <span class="keyword">new</span> Topological(G);</span><br><span class="line">      <span class="keyword">if</span> (!topological.hasOrder())</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Digraph is not acyclic.&quot;</span>);</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> v : topological.order()) &#123;</span><br><span class="line">          <span class="keyword">for</span> (DirectedEdge e : G.adj(v))</span><br><span class="line">              relax(e);</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(DirectedEdge e)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">int</span> v = e.from(), w = e.to();</span><br><span class="line"><span class="comment">// 改变不等式的方向</span></span><br><span class="line">      <span class="keyword">if</span> (distTo[w] &lt; distTo[v] + e.weight()) &#123;</span><br><span class="line">          distTo[w] = distTo[v] + e.weight();</span><br><span class="line">          edgeTo[w] = e;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h3 id="Bellman-Ford算法"><a href="#Bellman-Ford算法" class="headerlink" title="Bellman-Ford算法"></a>Bellman-Ford算法</h3><hr>
<p>我们已经知道了处理<code>权重</code>非负图的<code>Dijkstra算法</code>与处理<code>无环图</code>的算法,但如果遇见既含有环,<code>权重</code>也是负数的<code>加权有向图</code>该怎么办?</p>
<p><code>Bellman-Ford算法</code>就是用于处理<code>有环</code>且含有<code>负权重</code>的<code>加权有向图</code>的,它的原理是对图进行<code>V-1</code>次松弛操作,得到所有可能的最短路径.</p>
<p>要实现<code>Bellman-Ford算法</code>还需要以下数据结构: </p>
<ul>
<li>队列: 用于保存即将被松弛的顶点.</li>
</ul>
<ul>
<li>布尔值数组: 用来标记该顶点是否已经存在于队列中,以防止重复插入.</li>
</ul>
<p>我们将起点放入队列中,然后进入一个循环,每次循环都会从队列中取出一个顶点并对其进行松弛.为了保证算法在<code>V</code>轮后能够终止,需要能够动态地检测是否存在<code>负权重环</code>,如果找到了这个环则结束运行(也可以用一个变量动态记录轮数).</p>
<h4 id="负权重环的检测"><a href="#负权重环的检测" class="headerlink" title="负权重环的检测"></a>负权重环的检测</h4><hr>
<p>如果存在了一个从起点可达的<code>负权重环</code>,那么队列就永远不可能为空,为了从这个无尽的循环中解脱出来,算法需要能够动态地检测<code>负权重环</code>.</p>
<p><code>Bellman-Ford算法</code>也使用了<code>edgeTo[]</code>来存放<code>最短路径树</code>中的每一条边,我们根据<code>edgeTo[]</code>来复制一幅图并在该图中检测环.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">findNegativeCycle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">      <span class="keyword">int</span> V = edgeTo.length;</span><br><span class="line"><span class="comment">// 根据edgeTo[]来创建一幅加权有向图</span></span><br><span class="line">      EdgeWeightedDigraph spt = <span class="keyword">new</span> EdgeWeightedDigraph(V);</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; V; v++)</span><br><span class="line">          <span class="keyword">if</span> (edgeTo[v] != <span class="keyword">null</span>)</span><br><span class="line">              spt.addEdge(edgeTo[v]);</span><br><span class="line"><span class="comment">// 判断该图有没有环</span></span><br><span class="line">      EdgeWeightedDirectedCycle finder = <span class="keyword">new</span> EdgeWeightedDirectedCycle(spt);</span><br><span class="line">      cycle = finder.cycle();</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h4 id="实现代码-1"><a href="#实现代码-1" class="headerlink" title="实现代码"></a>实现代码</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BellmanFordSP</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span>[] distTo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> DirectedEdge[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 用于标记顶点是否在队列中</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span>[] onQueue;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 存放下次进行松弛操作的顶点的队列</span></span><br><span class="line">    <span class="keyword">private</span> Queue&lt;Integer&gt; queue;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 计算松弛操作的轮数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> cost;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 负权重环</span></span><br><span class="line">    <span class="keyword">private</span> Iterable&lt;DirectedEdge&gt; cycle;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BellmanFordSP</span><span class="params">(EdgeWeightedDigraph digraph, <span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.distTo = <span class="keyword">new</span> <span class="keyword">double</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> DirectedEdge[vertex];</span><br><span class="line">        <span class="keyword">this</span>.onQueue = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            distTo[v] = Double.POSITIVE_INFINITY;</span><br><span class="line">        distTo[s] = <span class="number">0.0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Bellman-Ford algorithm</span></span><br><span class="line">        queue = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        queue.add(s); <span class="comment">// 将起点放入队列</span></span><br><span class="line">        onQueue[s] = <span class="keyword">true</span>; <span class="comment">// 标记起点已在队列中</span></span><br><span class="line">		<span class="comment">// 当队列为空时或者发现负权重环时结束循环</span></span><br><span class="line">        <span class="keyword">while</span> (!queue.isEmpty() &amp;&amp; !hasNegativeCycle()) &#123;</span><br><span class="line">            <span class="keyword">int</span> v = queue.poll();</span><br><span class="line">            onQueue[v] = <span class="keyword">false</span>;</span><br><span class="line">            relax(digraph, v);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">relax</span><span class="params">(EdgeWeightedDigraph G, <span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (DirectedEdge e : G.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">int</span> w = e.to();</span><br><span class="line">            <span class="keyword">double</span> weight = distTo[v] + e.weight();</span><br><span class="line">            <span class="keyword">if</span> (distTo[w] &gt; weight) &#123;</span><br><span class="line">                distTo[w] = weight;</span><br><span class="line">                edgeTo[w] = e;</span><br><span class="line">				<span class="comment">// 将不在队列中的顶点w加到队列</span></span><br><span class="line">                <span class="keyword">if</span> (!onQueue[w]) &#123;</span><br><span class="line">                    queue.add(w);</span><br><span class="line">                    onQueue[w] = <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">			<span class="comment">// 动态检测负权重环,</span></span><br><span class="line">            <span class="keyword">if</span> (cost++ % G.vertex() == <span class="number">0</span>) &#123;</span><br><span class="line">                findNegativeCycle();</span><br><span class="line">                <span class="keyword">if</span> (hasNegativeCycle()) <span class="keyword">return</span>;  <span class="comment">// found a negative cycle</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><hr>
<p>解决<code>最短路径</code>问题一直都是<code>图论</code>的经典问题,本文中介绍的算法适用于不同的环境,在应用中应该根据不同的环境选择不同的算法.</p>
<table>
<thead>
<tr>
<th>算法</th>
<th>局限性</th>
<th>路径长度的比较次数(增长的数量级)</th>
<th>空间复杂度</th>
<th>优势</th>
</tr>
</thead>
<tbody><tr>
<td>Dijkstra</td>
<td>只能处理正权重</td>
<td>ElogV</td>
<td>V</td>
<td>最坏情况下仍有较好的性能</td>
</tr>
<tr>
<td>拓扑排序</td>
<td>只适用于无环图</td>
<td>E+V</td>
<td>V</td>
<td>实现简单,是无环图情况下的最优算法</td>
</tr>
<tr>
<td>Bellman-Ford</td>
<td>不能存在负权重环</td>
<td>E+V,最坏情况为VE</td>
<td>V</td>
<td>适用广泛</td>
</tr>
</tbody></table>
<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/44sp/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra’s algorithm - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm">Bellman–Ford algorithm - Wikipedia</a></li>
</ul>
<h3 id="图的那点事儿"><a href="#图的那点事儿" class="headerlink" title="图的那点事儿"></a>图的那点事儿</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">图的那点事儿(1)-无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">图的那点事儿(2)-有向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">图的那点事儿(3)-加权无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">图的那点事儿(4)-加权有向图</a></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/" class="post-title-link" itemprop="url">图的那点事儿(3)-加权无向图</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-25 18:00:00" itemprop="dateCreated datePublished" datetime="2017-07-25T18:00:00+08:00">2017-07-25</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Graph/" itemprop="url" rel="index"><span itemprop="name">Graph</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/</a></p>
</blockquote>
<h3 id="加权无向图"><a href="#加权无向图" class="headerlink" title="加权无向图"></a>加权无向图</h3><hr>
<p>所谓<code>加权图</code>,即每条<code>边</code>上都有着对应的<code>权重</code>,这个<code>权重</code>是正数也可以是负数,也不一定会和距离成正比.<code>加权无向图</code>的表示方法只需要对<code>无向图</code>的实现进行一下扩展.</p>
<ul>
<li>在使用<code>邻接矩阵</code>的方法中,可以用<code>边</code>的<code>权重</code>代替布尔值来作为矩阵的元素.</li>
</ul>
<ul>
<li>在使用<code>邻接表</code> 的方法中,可以在<code>链表</code>的<code>节点</code>中添加一个权重域.</li>
</ul>
<ul>
<li>在使用<code>邻接表</code>的方法中,将<code>边</code>抽象为一个<code>Edge</code>类,它包含了相连的两个<code>顶点</code>和它们的<code>权重</code>,<code>链表</code>中的每个元素都是一个<code>Edge</code>.</li>
</ul>
<p>我们使用第三种方法来实现<code>加权无向图</code>,它的数据表示如下图:</p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/edge-weighted-graph-representation.png" alt="加权无向图的表示"></p>
<h4 id="Edge的实现"><a href="#Edge的实现" class="headerlink" title="Edge的实现"></a>Edge的实现</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Edge</span> <span class="keyword">implements</span> <span class="title">Comparable</span>&lt;<span class="title">Edge</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> v;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> w;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">double</span> weight;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Edge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w, <span class="keyword">double</span> weight)</span> </span>&#123;</span><br><span class="line">        validateVertexes(v, w);</span><br><span class="line">        <span class="keyword">if</span> (Double.isNaN(weight)) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Weight is NaN.&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.v = v;</span><br><span class="line">        <span class="keyword">this</span>.w = w;</span><br><span class="line">        <span class="keyword">this</span>.weight = weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertexes</span><span class="params">(<span class="keyword">int</span>... vertexes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertexes.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (vertexes[i] &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">                        String.format(<span class="string">&quot;Vertex %d must be a nonnegative integer.&quot;</span>, vertexes[i]));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">weight</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">either</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> v;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">other</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertex == v)</span><br><span class="line">            <span class="keyword">return</span> w;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (vertex == w)</span><br><span class="line">            <span class="keyword">return</span> v;</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Illegal endpoint.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">compareTo</span><span class="params">(Edge that)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Double.compare(<span class="keyword">this</span>.weight, that.weight);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> String.format(<span class="string">&quot;%d-%d %.5f&quot;</span>, v, w, weight);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>Edge</code>类提供了<code>either()</code>与<code>other()</code>两个函数,在两个<code>顶点</code>都未知的情况下,可以调用<code>either()</code>获得<code>顶点v</code>,然后再调用<code>other(v)</code>来获得另一个<code>顶点</code>.</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/tree/master/src/main/java/chapter4_graphs/C4_3_MinimumSpanningTrees">本文中的所有完整代码点我查看</a></p>
</blockquote>
<h4 id="加权无向图的实现"><a href="#加权无向图的实现" class="headerlink" title="加权无向图的实现"></a>加权无向图的实现</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">EdgeWeightedGraph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String NEWLINE = System.getProperty(<span class="string">&quot;line.separator&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> vertexes;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> edges;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Bag&lt;Edge&gt;[] adj;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">EdgeWeightedGraph</span><span class="params">(<span class="keyword">int</span> vertexes)</span> </span>&#123;</span><br><span class="line">        validateVertexes(vertexes);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.vertexes = vertexes;</span><br><span class="line">        <span class="keyword">this</span>.edges = <span class="number">0</span>;</span><br><span class="line">        adj = (Bag&lt;Edge&gt;[]) <span class="keyword">new</span> Bag[vertexes];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertexes; i++)</span><br><span class="line">            adj[i] = <span class="keyword">new</span> Bag&lt;&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">EdgeWeightedGraph</span><span class="params">(Scanner scanner)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(scanner.nextInt());</span><br><span class="line">        <span class="keyword">int</span> edges = scanner.nextInt();</span><br><span class="line">        validateEdges(edges);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edges; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> v = scanner.nextInt();</span><br><span class="line">            <span class="keyword">int</span> w = scanner.nextInt();</span><br><span class="line">            <span class="keyword">double</span> weight = scanner.nextDouble();</span><br><span class="line">            addEdge(<span class="keyword">new</span> Edge(v, w, weight));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> vertexes;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> edges;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(Edge e)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> v = e.either();</span><br><span class="line">        <span class="keyword">int</span> w = e.other(v);</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        adj[v].add(e);</span><br><span class="line">        adj[w].add(e);</span><br><span class="line">        edges++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Edge&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">degree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Edge&gt; <span class="title">edges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Bag&lt;Edge&gt; list = <span class="keyword">new</span> Bag&lt;Edge&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertexes; v++) &#123;</span><br><span class="line">            <span class="keyword">int</span> selfLoops = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (Edge e : adj(v)) &#123;</span><br><span class="line">				<span class="comment">// 只添加一条边</span></span><br><span class="line">                <span class="keyword">if</span> (e.other(v) &gt; v) &#123;</span><br><span class="line">                    list.add(e);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 只添加一条自环的边</span></span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span> (e.other(v) == v) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (selfLoops % <span class="number">2</span> == <span class="number">0</span>) list.add(e);</span><br><span class="line">                    selfLoops++;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> list;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringBuilder s = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        s.append(vertexes + <span class="string">&quot; &quot;</span> + edges + NEWLINE);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertexes; v++) &#123;</span><br><span class="line">            s.append(v + <span class="string">&quot;: &quot;</span>);</span><br><span class="line">            <span class="keyword">for</span> (Edge e : adj[v]) &#123;</span><br><span class="line">                s.append(e + <span class="string">&quot;  &quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            s.append(NEWLINE);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> s.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertexes</span><span class="params">(<span class="keyword">int</span>... vertexes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertexes.length; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (vertexes[i] &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">                        String.format(<span class="string">&quot;Vertex %d must be a nonnegative integer.&quot;</span>, vertexes[i]));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateEdges</span><span class="params">(<span class="keyword">int</span> edges)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (edges &lt; <span class="number">0</span>) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of edges must be nonnegative.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= vertexes)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (vertexes - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码是对<code>无向图</code>的扩展,它将<code>邻接表</code>中的元素从<code>整数</code>变为了<code>Edge</code>,函数<code>edges()</code>返回了<code>边</code>的集合,由于是<code>无向图</code>所以每条<code>边</code>会出现两次,需要注意处理.</p>
<p><code>加权无向图</code>的实现还拥有以下特点: </p>
<ul>
<li>边的比较: <code>Edge</code>类实现了<code>Comparable</code>接口,它使用了<code>权重</code>来比较两条<code>边</code>的大小,所以<code>加权无向图</code>的自然次序就是权重次序.</li>
</ul>
<ul>
<li>自环: 该实现允许存在自环,并且<code>edges()</code>函数中对自环边进行了记录.</li>
</ul>
<ul>
<li>平行边: 该实现允许存在平行边,但可以用更复杂的方法来消除平行边,例如只保留平行边中的权重最小者.</li>
</ul>
<h3 id="最小生成树"><a href="#最小生成树" class="headerlink" title="最小生成树"></a>最小生成树</h3><hr>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/mst.png" alt="加权无向图的最小生成树"></p>
<p><code>最小生成树</code>是<code>加权无向图</code>的重要应用.<strong><code>图</code>的<code>生成树</code>是它的一棵含有其所有<code>顶点</code>的<code>无环连通子图</code>,<code>最小生成树</code>是它的一棵<code>权值</code>(所有边的权值之和)最小的<code>生成树</code>.</strong></p>
<p>在给定的一幅<code>加权无向图</code>$G = (V,E)$中,$(u,v)$代表连接<code>顶点u</code>与<code>顶点v</code>的<code>边</code>,也就是$(u,v) \in E$,而$w(u,v)$代表这条边的<code>权重</code>,若存在<code>T</code>为<code>E</code>的子集,也就是$T \subseteq E$,且为<code>无环图</code>,使得$w(T) = \sum_{(u,v) \in T}w(u,v)$ 的 $w(T)$ 最小,则<code>T</code>为<code>G</code>的<code>最小生成树</code>.</p>
<p><code>最小生成树</code>在一些情况下可能会存在多个,例如,给定一幅图<code>G</code>,当它的所有边的<code>权重</code>都相同时,那么<code>G</code>的所有<code>生成树</code>都是<code>最小生成树</code>,当所有边的<code>权重</code>互不相同时,将会只有一个<code>最小生成树</code>.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Multiple_minimum_spanning_trees.svg/316px-Multiple_minimum_spanning_trees.svg.png" alt="多个最小生成树的情况"></p>
<h3 id="切分定理"><a href="#切分定理" class="headerlink" title="切分定理"></a>切分定理</h3><hr>
<p><strong><code>切分定理</code>将图中的所有<code>顶点</code>切分为两个集合(两个非空且不重叠的集合),检查两个集合的所有边并识别哪条边应属于图的<code>最小生成树</code>.</strong></p>
<p>一种比较简单的切分方法即通过<strong>指定一个顶点集并隐式地认为它的补集为另一个顶点集来指定一个切分.</strong></p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/cut-property.png" alt="白色与灰色顶点代表了不同的顶点集"></p>
<p><code>切分定理</code>也表明了对于每一种切分,<code>权重</code>最小的<code>横切边(一条连接两个属于不同集合的顶点的边)</code>必然属于<code>最小生成树</code>.</p>
<p><code>切分定理</code>是解决<code>最小生成树</code>问题的所有算法的基础,<strong>使用<code>切分定理</code>找到<code>最小生成树</code>的一条边,不断重复直到找到<code>最小生成树</code>的所有边.</strong></p>
<p>这些算法可以说都是<code>贪心算法</code>,算法的每一步都是在找最优解(<code>权值</code>最小的<code>横切边</code>),而<strong>解决<code>最小生成树</code>的各种算法不同之处仅在于保存切分和判定<code>权重</code>最小的<code>横切边</code>的方式.</strong></p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/mst-greedy.png" alt="生成最小生成树的过程,权值最小的横切边将会被标记为黑色"></p>
<h3 id="Prim算法"><a href="#Prim算法" class="headerlink" title="Prim算法"></a>Prim算法</h3><hr>
<p><code>Prim算法</code>是用于解决<code>最小生成树</code>的算法之一,算法的每一步都会为一棵生长中的<code>树</code>添加一条边.一开始这棵树只有一个<code>顶点</code>,然后会一直添加到$V - 1$条边,<strong>每次总是将下一条连接<code>树</code>中的<code>顶点</code>与不在<code>树</code>中的<code>顶点</code>且<code>权重</code>最小的边加入到<code>树</code>中(也就是由<code>树</code>中<code>顶点</code>所定义的切分中的一条<code>横切边</code>).</strong></p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/prim.png"></p>
<p>实现<code>Prim算法</code>还需要借助以下数据结构: </p>
<ul>
<li>布尔值数组: 用于记录<code>顶点</code>是否已在<code>树</code>中.</li>
</ul>
<ul>
<li>队列: 使用一条队列来保存<code>最小生成树</code>中的边,也可以使用一个由<code>顶点</code>索引的<code>Edge</code>对象的数组.</li>
</ul>
<ul>
<li>优先队列: 优先队列用于保存<code>横切边</code>,优先队列的性质可以每次取出<code>权值</code>最小的<code>横切边</code>.</li>
</ul>
<h4 id="延时实现"><a href="#延时实现" class="headerlink" title="延时实现"></a>延时实现</h4><hr>
<p>当我们连接新加入<code>树</code>中的<code>顶点</code>与其他已经在<code>树</code>中<code>顶点</code>的所有边都失效了(由于两个<code>顶点</code>都已在<code>树</code>中,所以这是一条失效的<code>横切边</code>).我们需要处理这种情况,<strong>即使实现对无效边采取忽略(不加入到优先队列中),而延时实现会把无效边留在优先队列中,等到要删除优先队列中的数据时再进行有效性检查.</strong></p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/prim-lazy.png" alt="Prim延时实现的运行轨迹"></p>
<p>上图为<code>Prim算法</code>延时实现的轨迹图,它的步骤如下: </p>
<ul>
<li>将<code>顶点0</code>添加到<code>最小生成树</code>中,将它的<code>邻接表</code>中的所有边添加到优先队列中(将<code>横切边</code>添加到优先队列).</li>
</ul>
<ul>
<li>将<code>顶点7</code>和边<code>0-7</code>添加到<code>最小生成树</code>中,将<code>顶点</code>的<code>邻接表</code>中的所有边添加到优先队列中.</li>
</ul>
<ul>
<li>将<code>顶点1</code>和边<code>1-7</code>添加到<code>最小生成树</code>中,将<code>顶点</code>的<code>邻接表</code>中的所有边添加到优先队列中.</li>
</ul>
<ul>
<li>将<code>顶点2</code>和边<code>0-2</code>添加到<code>最小生成树</code>中,将边<code>2-3</code>和<code>6-2</code>添加到优先队列中,边<code>2-7</code>和<code>1-2</code>失效.</li>
</ul>
<ul>
<li>将<code>顶点3</code>和边<code>2-3</code>添加到<code>最小生成树</code>中,将边<code>3-6</code>添加到优先队列之中,边<code>1-3</code>失效.</li>
</ul>
<ul>
<li>将<code>顶点5</code>和边<code>5-7</code>添加到<code>最小生成树</code>中,将边<code>4-5</code>添加到优先队列中,边<code>1-5</code>失效.</li>
</ul>
<ul>
<li>从优先队列中删除失效边<code>1-3</code>,<code>1-5</code>,<code>2-7</code>.</li>
</ul>
<ul>
<li>将<code>顶点4</code>和边<code>4-5</code>添加到<code>最小生成树</code>中,将边<code>6-4</code>添加到优先队列中,边<code>4-7</code>,<code>0-4</code>失效.</li>
</ul>
<ul>
<li>从优先队列中删除失效边<code>1-2</code>,<code>4-7</code>,<code>0-4</code>.</li>
</ul>
<ul>
<li>将<code>顶点6</code>和边<code>6-2</code>添加到<code>最小生成树</code>中,和<code>顶点6</code>关联的其他边失效.</li>
</ul>
<ul>
<li>在添加<code>V</code>个顶点与<code>V - 1</code>条边之后,<code>最小生成树</code>就构造完成了,优先队列中剩余的边都为失效边.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LazyPrimMST</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> EdgeWeightedGraph graph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 记录最小生成树的总权重</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> weight;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 存储最小生成树的边</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Edge&gt; mst;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 标记这个顶点在树中</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 存储横切边的优先队列</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> PriorityQueue&lt;Edge&gt; pq;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">LazyPrimMST</span><span class="params">(EdgeWeightedGraph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        mst = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        pq = <span class="keyword">new</span> PriorityQueue&lt;&gt;();</span><br><span class="line">        marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) prim(v);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">prim</span><span class="params">(<span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">        scanAndPushPQ(s);</span><br><span class="line">        <span class="keyword">while</span> (!pq.isEmpty()) &#123;</span><br><span class="line">            Edge edge = pq.poll();  <span class="comment">// 取出权重最小的横切边</span></span><br><span class="line">            <span class="keyword">int</span> v = edge.either(), w = edge.other(v);  </span><br><span class="line">            <span class="keyword">assert</span> marked[v] || marked[w];</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (marked[v] &amp;&amp; marked[w])</span><br><span class="line">                <span class="keyword">continue</span>; <span class="comment">// 忽略失效边</span></span><br><span class="line"></span><br><span class="line">            mst.add(edge); <span class="comment">// 添加边到最小生成树中</span></span><br><span class="line">            weight += edge.weight(); <span class="comment">// 更新总权重</span></span><br><span class="line">			<span class="comment">// 继续将非树顶点加入到树中并更新横切边</span></span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) scanAndPushPQ(v); </span><br><span class="line">            <span class="keyword">if</span> (!marked[w]) scanAndPushPQ(w); </span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 标记顶点到树中,并且添加横切边到优先队列</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">scanAndPushPQ</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">assert</span> !marked[v];</span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line">        <span class="keyword">for</span> (Edge e : graph.adj(v))</span><br><span class="line">            <span class="keyword">if</span> (!marked[e.other(v)]) pq.add(e);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Edge&gt; <span class="title">edges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mst;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">weight</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="即时实现"><a href="#即时实现" class="headerlink" title="即时实现"></a>即时实现</h4><hr>
<p>在即时实现中,将<code>v</code>添加到树中时,对于每个<code>非树顶点w</code>,<strong>不需要在优先队列中保存所有从<code>w</code>到<code>树顶点</code>的边,而只需要保存其中<code>权重</code>最小的边,所以在将<code>v</code>添加到<code>树</code>中后,要检查是否需要更新这条<code>权重</code>最小的边(如果<code>v-w</code>的<code>权重</code>更小的话).</strong></p>
<p>也可以认为只会在优先队列中保存每个<code>非树顶点w</code>的一条边(也是<code>权重</code>最小的那条边),将<code>w</code>和<code>树顶点</code>连接起来的其他<code>权重</code>较大的边迟早都会失效,所以没必要在优先队列中保存它们.</p>
<p>要实现即时版的<code>Prim算法</code>,需要使用两个顶点索引的数组<code>edgeTo[]</code>和<code>distTo[]</code>与一个索引优先队列,它们具有以下性质: </p>
<ul>
<li>如果<code>顶点v</code>不在树中但至少含有一条边和树相连,那么<code>edgeTo[v]</code>是将<code>v</code>和树连接的最短边,<code>distTo[v]</code>为这条边的<code>权重</code>.</li>
</ul>
<ul>
<li>所有这类<code>顶点v</code>都保存在索引优先队列中,索引<code>v</code>关联的值是<code>edgeTo[v]</code>的边的<code>权重</code>.</li>
</ul>
<ul>
<li>索引优先队列中的最小键即是<code>权重</code>最小的<code>横切边</code>的<code>权重</code>,而和它相关联的顶点<code>v</code>就是下一个将要被添加到<code>树</code>中的<code>顶点</code>.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/prim-eager.png" alt="即时实现Prim算法的运行轨迹"></p>
<ul>
<li>将<code>顶点0</code>添加到<code>最小生成树</code>之中,将它的<code>邻接表</code>中的所有边添加到优先队列中(这些边是目前唯一已知的横切边).</li>
</ul>
<ul>
<li>将<code>顶点7</code>和边<code>0-7</code>添加到<code>最小生成树</code>,将边<code>1-7</code>和<code>5-7</code>添加到优先队列中,将连接<code>顶点4</code>与树的最小边由<code>0-4</code>替换为<code>4-7</code>.</li>
</ul>
<ul>
<li>将<code>顶点1</code>和边<code>1-7</code>添加到<code>最小生成树</code>,将边<code>1-3</code>添加到优先队列.</li>
</ul>
<ul>
<li>将<code>顶点2</code>和边<code>0-2</code>添加到最小生成树,将连接<code>顶点6</code>与树的最小边由<code>0-6</code>替换为<code>6-2</code>,将连接<code>顶点3</code>与树的最小边由<code>1-3</code>替换为<code>2-3</code>.</li>
</ul>
<ul>
<li>将<code>顶点3</code>和边<code>2-3</code>添加到<code>最小生成树</code>.</li>
</ul>
<ul>
<li>将<code>顶点5</code>和边<code>5-7</code>添加到<code>最小生成树</code>,将连接<code>顶点4</code>与树的最小边<code>4-7</code>替换为<code>4-5</code>.</li>
</ul>
<ul>
<li>将<code>顶点4</code>和边<code>4-5</code>添加到<code>最小生成树</code>.</li>
</ul>
<ul>
<li>将<code>顶点6</code>和边<code>6-2</code>添加到<code>最小生成树</code>.</li>
</ul>
<ul>
<li>在添加了<code>V - 1</code>条边之后,<code>最小生成树</code>构造完成并且优先队列为空.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrimMST</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> EdgeWeightedGraph graph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 存放最小生成树中的边</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Edge[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 每条边对应的权重</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">double</span>[] distTo;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> IndexMinPQ&lt;Double&gt; pq;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PrimMST</span><span class="params">(EdgeWeightedGraph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> Edge[vertex];</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.pq = <span class="keyword">new</span> IndexMinPQ&lt;&gt;(vertex);</span><br><span class="line">        <span class="keyword">this</span>.distTo = <span class="keyword">new</span> <span class="keyword">double</span>[vertex];</span><br><span class="line">		<span class="comment">// 将权重数组初始化为无穷大</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">            distTo[i] = Double.POSITIVE_INFINITY;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) prim(v);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">prim</span><span class="params">(<span class="keyword">int</span> s)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 将起点设为0.0并加入到优先队列</span></span><br><span class="line">        distTo[s] = <span class="number">0.0</span>;</span><br><span class="line">        pq.insert(s, distTo[s]);</span><br><span class="line">        <span class="keyword">while</span> (!pq.isEmpty()) &#123;</span><br><span class="line">			<span class="comment">// 取出权重最小的边,优先队列中存的顶点是与树相连的非树顶点,</span></span><br><span class="line">			<span class="comment">// 同时它也是下一次要加入到树中的顶点</span></span><br><span class="line">            <span class="keyword">int</span> v = pq.delMin();</span><br><span class="line">            scan(v);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">scan</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 将顶点加入到树中</span></span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Edge e : graph.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">int</span> w = e.other(v);</span><br><span class="line">			<span class="comment">// 忽略失效边</span></span><br><span class="line">            <span class="keyword">if</span> (marked[w]) <span class="keyword">continue</span>;</span><br><span class="line">			<span class="comment">// 如果w与连接树顶点的边的权重小于其他w连接树顶点的边</span></span><br><span class="line">			<span class="comment">// 则进行替换更新</span></span><br><span class="line">            <span class="keyword">if</span> (e.weight() &lt; distTo[w]) &#123;</span><br><span class="line">                distTo[w] = e.weight();</span><br><span class="line">                edgeTo[w] = e;</span><br><span class="line">                <span class="keyword">if</span> (pq.contains(w))</span><br><span class="line">                    pq.decreaseKey(w, distTo[w]);</span><br><span class="line">                <span class="keyword">else</span></span><br><span class="line">                    pq.insert(w, distTo[w]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Edge&gt; <span class="title">edges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Queue&lt;Edge&gt; mst = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; edgeTo.length; v++) &#123;</span><br><span class="line">            Edge e = edgeTo[v];</span><br><span class="line">            <span class="keyword">if</span> (e != <span class="keyword">null</span>) &#123;</span><br><span class="line">                mst.add(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> mst;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">weight</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">double</span> weight = <span class="number">0.0</span>;</span><br><span class="line">        <span class="keyword">for</span> (Edge e : edges())</span><br><span class="line">            weight += e.weight();</span><br><span class="line">        <span class="keyword">return</span> weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不管是<code>延迟实现</code>还是<code>即时实现</code>,<code>Prim算法</code>的规律就是: <strong>在<code>树</code>的生长过程中,都是通过连接一个和新加入的<code>顶点</code>相邻的<code>顶点</code>.当新加入的<code>顶点</code>周围没有<code>非树顶点</code>时,树的生长又会从另一部分开始.</strong></p>
<h3 id="Kruskal算法"><a href="#Kruskal算法" class="headerlink" title="Kruskal算法"></a>Kruskal算法</h3><hr>
<p><code>Kruskal算法</code>的思想是<strong>按照边的<code>权重</code>顺序由小到大处理它们</strong>,将边添加到<code>最小生成树</code>,加入的边不会与已经在<code>树</code>中的边构成环,直到<code>树</code>中含有<code>V - 1</code>条边为止.<strong>这些边会逐渐由一片<code>森林</code>合并为一棵<code>树</code></strong>,也就是我们需要的<code>最小生成树</code>.</p>
<p><img src="http://algs4.cs.princeton.edu/43mst/images/kruskal.png" alt="Kruskal算法的运行轨迹"></p>
<h4 id="与Prim算法的区别"><a href="#与Prim算法的区别" class="headerlink" title="与Prim算法的区别"></a>与Prim算法的区别</h4><hr>
<ul>
<li><code>Prim算法</code>是一条边一条边地来构造<code>最小生成树</code>,每一步都会为<code>树</code>中添加一条边.</li>
</ul>
<ul>
<li><code>Kruskal算法</code>构造<code>最小生成树</code>也是一条边一条边地添加,但不同的是它寻找的边会连接一片<code>森林</code>中的两棵<code>树</code>.从一片由<code>V</code>棵单<code>顶点</code>的树构成的<code>森林</code>开始并不断地将两棵<code>树</code>合并(可以找到的最短边)直到只剩下一棵<code>树</code>,它就是<code>最小生成树</code>.</li>
</ul>
<h4 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h4><hr>
<p>要实现<code>Kruskal算法</code>需要借助<code>Union-Find</code>数据结构,它是一种树型的数据结构,用于处理一些不相交集合的合并与查询问题.</p>
<p>关于<code>Union-Find</code>的更多资料可以参考下面的链接: </p>
<ul>
<li><a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/blob/15ae228a1bc6a75465a96681caaa93eff3462327/src/main/java/chapter1_fundamentals/C1_5_UnionFind/UF.java">Union-Find简单实现</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure">Disjoint-set data structure - Wikipedia</a></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">KruskalMST</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 这条队列用于记录最小生成树中的边集</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Edge&gt; mst;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">double</span> weight;</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">KruskalMST</span><span class="params">(EdgeWeightedGraph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.mst = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="comment">// 创建一个优先队列,并将图的所有边添加到优先队列中</span></span><br><span class="line">        PriorityQueue&lt;Edge&gt; pq = <span class="keyword">new</span> PriorityQueue&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (Edge e : graph.edges()) &#123;</span><br><span class="line">            pq.add(e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">		<span class="comment">// 创建一个Union-Find</span></span><br><span class="line">        UF uf = <span class="keyword">new</span> UF(vertex);</span><br><span class="line">		<span class="comment">// 一条一条地添加边到最小生成树,直到添加了 V - 1条边</span></span><br><span class="line">        <span class="keyword">while</span> (!pq.isEmpty() &amp;&amp; mst.size() &lt; vertex - <span class="number">1</span>) &#123;</span><br><span class="line">			<span class="comment">// 取出权重最小的边</span></span><br><span class="line">            Edge e = pq.poll();</span><br><span class="line">            <span class="keyword">int</span> v = e.either();</span><br><span class="line">            <span class="keyword">int</span> w = e.other(v);</span><br><span class="line">            <span class="comment">// 如果这条边的两个顶点不在一个分量中(对于union-find数据结构中而言)</span></span><br><span class="line">            <span class="keyword">if</span> (!uf.connected(v, w)) &#123;</span><br><span class="line">				<span class="comment">// 将v和w归并(对于union-find数据结构中而言),然后将边添加进树中,并计算更新权重</span></span><br><span class="line">                uf.union(v, w); </span><br><span class="line">                mst.add(e);</span><br><span class="line">                weight += e.weight();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Edge&gt; <span class="title">edges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mst;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">double</span> <span class="title">weight</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> weight;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码实现的<code>Kruskal算法</code>使用了一条队列来保存<code>最小生成树</code>的边集,一条优先队列来保存还未检查的边,一个<code>Union-Find</code>来判断失效边.</p>
<h4 id="性能比较"><a href="#性能比较" class="headerlink" title="性能比较"></a>性能比较</h4><hr>
<table>
<thead>
<tr>
<th>算法</th>
<th>空间复杂度</th>
<th>时间复杂度</th>
</tr>
</thead>
<tbody><tr>
<td>Prim(延时)</td>
<td>E</td>
<td>ElogE</td>
</tr>
<tr>
<td>Prim(即时)</td>
<td>V</td>
<td>ElogV</td>
</tr>
<tr>
<td>Kruskal</td>
<td>E</td>
<td>ElogE</td>
</tr>
</tbody></table>
<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Minimum_spanning_tree">Minimum spanning tree - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/43mst/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<h3 id="图的那点事儿"><a href="#图的那点事儿" class="headerlink" title="图的那点事儿"></a>图的那点事儿</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">图的那点事儿(1)-无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">图的那点事儿(2)-有向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">图的那点事儿(3)-加权无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">图的那点事儿(4)-加权有向图</a></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/" class="post-title-link" itemprop="url">图的那点事儿(2)-有向图</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-23 11:00:00" itemprop="dateCreated datePublished" datetime="2017-07-23T11:00:00+08:00">2017-07-23</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Graph/" itemprop="url" rel="index"><span itemprop="name">Graph</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <blockquote>
<p>本文作者为: <a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun</a>.转载请务必将下面这段话置于文章开头处(保留超链接).<br>本文转发自<a target="_blank" rel="noopener" href="https://sylvanassun.github.io/">SylvanasSun Blog</a>,原文链接: <a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/</a></p>
</blockquote>
<h3 id="有向图的性质"><a href="#有向图的性质" class="headerlink" title="有向图的性质"></a>有向图的性质</h3><hr>
<p><code>有向图</code>与<code>无向图</code>不同,<strong>它的<code>边</code>是单向的,每条边所连接的两个顶点都是一个有序对,它们的邻接性是单向的.</strong></p>
<p>在<code>有向图</code>中,一条<code>有向边</code><strong>由第一个<code>顶点</code>指出并指向第二个<code>顶点</code></strong>,<strong>一个<code>顶点</code>的<code>出度</code>为由该<code>顶点</code>指出的<code>边</code>的总数;一个<code>顶点</code>的<code>入度</code>为指向该<code>顶点</code>的边的总数</strong>.</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/digraph-anatomy.png" alt="有向图的解析"></p>
<p><code>v-&gt;w</code>表示一条由<code>v</code>指向<code>w</code>的边,在一幅<code>有向图</code>中,两个<code>顶点</code>的关系可能有以下四种(特殊图除外): </p>
<ol>
<li>没有<code>边</code>相连.</li>
</ol>
<ol start="2">
<li>存在一条从<code>v</code>到<code>w</code>的<code>边</code>: <code>v-&gt;w</code>.</li>
</ol>
<ol start="3">
<li>存在一条从<code>w</code>到<code>v</code>的<code>边</code>: <code>w-&gt;v</code>.</li>
</ol>
<ol start="4">
<li>既存在<code>v-&gt;w</code>,也存在<code>w-&gt;v</code>,也就是一条<code>双向边</code>.</li>
</ol>
<p>当存在从<code>v</code>到<code>w</code>的<code>有向路径</code>时,称<code>顶点w</code>能够由<code>顶点v</code>达到.但在<code>有向图</code>中,由<code>v</code>能够到达<code>w</code>并不意味着由<code>w</code>也能到达<code>v</code>(但每个<code>顶点</code>都是能够到达它自己的).</p>
<h3 id="有向图的实现"><a href="#有向图的实现" class="headerlink" title="有向图的实现"></a>有向图的实现</h3><hr>
<p><code>有向图</code>的实现与<code>无向图</code>差不多,只不过在<code>边</code>的方向上有所不同.(本文中的所有完整代码可以在我的<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/tree/master/src/main/java/chapter4_graphs/C4_2_DirectedGraphs">GitHub</a>中查看)</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/digraph-api.png" alt="有向图的API"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Digraph</span> <span class="keyword">implements</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String NEWLINE = System.getProperty(<span class="string">&quot;line.separator&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of vertices in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> vertex;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of edges in this digraph</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> edge;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// adj[v] = adjacency list for vertex v</span></span><br><span class="line">    <span class="keyword">private</span> Bag&lt;Integer&gt;[] adj;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// indegree[v] = indegree of vertex v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] indegree;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">        <span class="keyword">this</span>.edge = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.indegree = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.adj = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">            adj[i] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(Scanner scanner)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (scanner == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Scanner must be not null.&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">int</span> vertex = scanner.nextInt();</span><br><span class="line">            validateVertex(vertex);</span><br><span class="line">            <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">            <span class="keyword">this</span>.indegree = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">            <span class="keyword">this</span>.adj = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">                adj[i] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">int</span> edge = scanner.nextInt();</span><br><span class="line">            validateEdge(edge);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edge; i++) &#123;</span><br><span class="line">                <span class="keyword">int</span> v = scanner.nextInt();</span><br><span class="line">                <span class="keyword">int</span> w = scanner.nextInt();</span><br><span class="line">                addEdge(v, w);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchElementException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Invalid input format in Digraph constructor&quot;</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Digraph</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(digraph.vertex);</span><br><span class="line">        <span class="keyword">this</span>.edge = digraph.edge;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">this</span>.indegree[v] = digraph.indegree(v);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            Stack&lt;Integer&gt; reverse = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(v))</span><br><span class="line">                reverse.push(w);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : reverse)</span><br><span class="line">                <span class="keyword">this</span>.adj[v].add(w);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> vertex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> edge;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 注意这里与无向图不同,只在v的邻接表中添加了w</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        adj[v].add(w);</span><br><span class="line">		<span class="comment">// w的入度+ 1</span></span><br><span class="line">        indegree[w]++;</span><br><span class="line">        edge++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> indegree[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * v的出度就是它邻接表中的顶点数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">outdegree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@Deprecated</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">degree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adj[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 它返回该有向图的一个副本,但所有边的方向都会被反转.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Digraph <span class="title">reverse</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Digraph reverse = <span class="keyword">new</span> Digraph(vertex);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : adj[v]) &#123;</span><br><span class="line">                reverse.addEdge(w, v);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> reverse;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        sb.append(String.format(<span class="string">&quot;Vertexes: %s, Edges: %s&quot;</span>, vertex, edge));</span><br><span class="line">        sb.append(NEWLINE);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            sb.append(String.format(<span class="string">&quot;vertex %d, &quot;</span>, v));</span><br><span class="line">            sb.append(String.format(<span class="string">&quot;indegree: %d, outdegree: %d&quot;</span>, indegree(v), outdegree(v)));</span><br><span class="line">            sb.append(NEWLINE);</span><br><span class="line">            sb.append(<span class="string">&quot;adjacent point: &quot;</span>);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : adj[v])</span><br><span class="line">                sb.append(w).append(<span class="string">&quot; &quot;</span>);</span><br><span class="line"></span><br><span class="line">            sb.append(NEWLINE);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateEdge</span><span class="params">(<span class="keyword">int</span> edge)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (edge &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of edges in a Digraph must be nonnegative.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of vertex in a Digraph must be nonnegative.&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="可达性"><a href="#可达性" class="headerlink" title="可达性"></a>可达性</h3><hr>
<p>对于”是否存在一条从集合中的任意<code>顶点</code>到达给定<code>顶点v</code>的有向路径?”等类似问题,可以使用<code>深度优先搜索</code>或<code>广度优先搜索</code>(与<code>无向图</code>的实现一致,只不过传入的<code>图</code>的类型不同),<code>有向图</code>生成的搜索轨迹甚至要比<code>无向图</code>还要简单.</p>
<p>对于<code>可达性分析</code>的一个典型应用就是内存管理系统.例如,<code>JVM</code>使用<code>多点可达性分析</code>的方法来判断一个<code>对象</code>是否可以进行回收: 所有<code>对象</code>组成一幅<code>有向图</code>,其中有多个<code>Root顶点</code>(它是由<code>JVM</code>自己决定的)作为<code>起点</code>,如果一个<code>对象</code>从<code>Root顶点</code>不可达,那么这个<code>对象</code>就可以进行回收了.</p>
<h3 id="环"><a href="#环" class="headerlink" title="环"></a>环</h3><hr>
<p>在与<code>有向图</code>相关的实际应用中,<code>有向环</code>特别的重要.我们需要知道一幅<code>有向图</code>中是否包含<code>有向环</code>.在任务调度问题或其他许多问题中会不允许存在<code>有向环</code>,所以对于<code>环</code>的检测是很重要的.</p>
<p>使用<code>深度优先搜索</code>解决这个问题并不困难,递归调用隐式使用的栈表示的正是”当前”正在遍历的<code>有向路径</code>,一旦找到了一条<code>边v-&gt;w</code>且<code>w</code>已经存在于栈中,就等于找到了一个<code>环</code>(栈表示的是一条由<code>w</code>到<code>v</code>的<code>有向路径</code>,而<code>v-&gt;w</code>正好补全了这个<code>环</code>).</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DirectedCycle</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Digraph digraph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has vertex v been marked?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// edgeTo[v] = previous vertex on path to v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] edgeTo;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// onStack[v] = is vertex on the stack?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] onStack;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// directed cycle (or null if no such cycle)</span></span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; cycle;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DirectedCycle</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.digraph = digraph;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.onStack = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">			<span class="comment">// 已经找到环时就不再需要继续搜索了</span></span><br><span class="line">            <span class="keyword">if</span> (!marked[v] &amp;&amp; cycle == <span class="keyword">null</span>)</span><br><span class="line">                dfs(v);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasCycle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cycle != <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">cycle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cycle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">        onStack[vertex] = <span class="keyword">true</span>; <span class="comment">// 用于模拟递归调用栈</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (cycle != <span class="keyword">null</span>)</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            <span class="keyword">else</span> <span class="keyword">if</span> (!marked[w]) &#123;</span><br><span class="line">                edgeTo[w] = vertex;</span><br><span class="line">                dfs(w);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (onStack[w]) &#123;</span><br><span class="line">				<span class="comment">// 当w已被标记且在栈中时: 找到环</span></span><br><span class="line">                cycle = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> x = vertex; x != w; x = edgeTo[x])</span><br><span class="line">                    cycle.push(x);</span><br><span class="line">                cycle.push(w);</span><br><span class="line">                cycle.push(vertex);</span><br><span class="line">                <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">()</span></span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">// 这条路径已经到头,从栈中弹出</span></span><br><span class="line">        onStack[vertex] = <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// certify that digraph has a directed cycle if it reports one</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (hasCycle()) &#123;</span><br><span class="line">            <span class="comment">// verify cycle</span></span><br><span class="line">            <span class="keyword">int</span> first = -<span class="number">1</span>, last = -<span class="number">1</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> v : cycle()) &#123;</span><br><span class="line">                <span class="keyword">if</span> (first == -<span class="number">1</span>) first = v;</span><br><span class="line">                last = v;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (first != last) &#123;</span><br><span class="line">                System.err.printf(<span class="string">&quot;cycle begins with %d and ends with %d\n&quot;</span>, first, last);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="拓扑排序"><a href="#拓扑排序" class="headerlink" title="拓扑排序"></a>拓扑排序</h3><hr>
<p><code>拓扑排序</code>等价于计算优先级限制下的调度问题的,所谓优先级限制的调度问题即是在给定一组需要完成的任务与关于任务完成的先后次序的优先级限制,需要在满足限制条件的前提下来安排任务.</p>
<p><code>拓扑排序</code>需要的是一幅<code>有向无环图</code>,如果这幅<code>图</code>中含有<code>环</code>,那么它肯定不是<code>拓扑有序</code>的(一个带有环的调度问题是无解的).</p>
<p>在学习<code>拓扑排序</code>之前,需要先知道<code>顶点</code>的排序.</p>
<h4 id="顶点排序"><a href="#顶点排序" class="headerlink" title="顶点排序"></a>顶点排序</h4><hr>
<p>使用<code>深度优先搜索</code>来记录<code>顶点排序</code>是一个很好的选择(正好只会访问每个<code>顶点</code>一次),我们借助一些<code>数据结构</code>来保存<code>顶点排序</code>的顺序: </p>
<ul>
<li>前序: 在递归调用之前将<code>顶点</code>加入队列.</li>
</ul>
<ul>
<li>后序: 在递归调用之后将<code>顶点</code>加入队列.</li>
</ul>
<ul>
<li>逆后序: 在递归调用之后将<code>顶点</code>压入栈.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/depth-first-orders.png" alt="顶点排序的轨迹"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DepthFirstOrder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has v been marked in dfs?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// pre[v]    = preorder  number of v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] pre;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// post[v]   = postorder number of v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] post;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// vertices in preorder</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Integer&gt; preorder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// vertices in postorder</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Queue&lt;Integer&gt; postorder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// counter or preorder numbering</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> preCounter;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// counter for postorder numbering</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> postCounter;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DepthFirstOrder</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.pre = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.post = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.preorder = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.postorder = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) dfs(v);</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">()</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">pre</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> pre[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">post</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> post[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">post</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> postorder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">pre</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> preorder;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 逆后序,遍历后序队列并压入栈中</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">reversePost</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Stack&lt;Integer&gt; reverse = <span class="keyword">new</span> Stack&lt;Integer&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : postorder)</span><br><span class="line">            reverse.push(v);</span><br><span class="line">        <span class="keyword">return</span> reverse;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">		<span class="comment">// 前序</span></span><br><span class="line">        pre[vertex] = preCounter++;</span><br><span class="line">        preorder.add(vertex);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w])</span><br><span class="line">                dfs(w);</span><br><span class="line">        &#125;</span><br><span class="line">		<span class="comment">// 后序</span></span><br><span class="line">        post[vertex] = postCounter++;</span><br><span class="line">        postorder.add(vertex);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// check that pre() and post() are consistent with pre(v) and post(v)</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that post(v) is consistent with post()</span></span><br><span class="line">        <span class="keyword">int</span> r = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : post()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (post(v) != r) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;post(v) and post() inconsistent&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            r++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that pre(v) is consistent with pre()</span></span><br><span class="line">        r = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : pre()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (pre(v) != r) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;pre(v) and pre() inconsistent&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            r++;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="拓扑排序的实现"><a href="#拓扑排序的实现" class="headerlink" title="拓扑排序的实现"></a>拓扑排序的实现</h4><hr>
<p>所谓<code>拓扑排序</code>就是<code>无环有向图</code>的<code>逆后序</code>,现在已经知道了如何检测<code>环</code>与<code>顶点排序</code>,那么实现<code>拓扑排序</code>就很简单了.</p>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/topological-sort.png"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Topological</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// topological order</span></span><br><span class="line">    <span class="keyword">private</span> Iterable&lt;Integer&gt; order;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// rank[v] = position of vertex v in topological order</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] rank;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Topological</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        DirectedCycle directedCycle = <span class="keyword">new</span> DirectedCycle(digraph);</span><br><span class="line">		<span class="comment">// 只有这幅图没有环时,才进行计算拓扑排序</span></span><br><span class="line">        <span class="keyword">if</span> (!directedCycle.hasCycle()) &#123;</span><br><span class="line">            DepthFirstOrder depthFirstOrder = <span class="keyword">new</span> DepthFirstOrder(digraph);</span><br><span class="line">			<span class="comment">// 拓扑排序即是逆后序</span></span><br><span class="line">            order = depthFirstOrder.reversePost();</span><br><span class="line">            rank = <span class="keyword">new</span> <span class="keyword">int</span>[digraph.vertex()];</span><br><span class="line">            <span class="keyword">int</span> i = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> v : order)</span><br><span class="line">                rank[v] = i++;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">order</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> order;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> order != <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">rank</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">if</span> (hasOrder()) <span class="keyword">return</span> rank[v];</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = rank.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="强连通性"><a href="#强连通性" class="headerlink" title="强连通性"></a>强连通性</h3><hr>
<p>在一幅<code>无向图</code>中,如果有一条路径连接顶点<code>v</code>和<code>w</code>,则它们就是<code>连通</code>的(既可以从<code>w</code>到达<code>v</code>,也可以从<code>v</code>到达<code>w</code>).但在<code>有向图</code>中,如果从顶点<code>v</code>有一条有向路径到达<code>w</code>,则<code>w</code>是从<code>v</code>可达的,但从<code>w</code>到达<code>v</code>的路径可能存在也可能不存在.</p>
<p><strong><code>强连通性</code>就是两个顶点<code>v</code>和<code>w</code>是互相可达的.</strong><code>有向图</code>中的<code>强连通性</code>具有以下性质: </p>
<ul>
<li>自反性: 任意<code>顶点v</code>和自己都是<code>强连通性</code>的(<code>有向图</code>中顶点都是自己可达的).</li>
</ul>
<ul>
<li>对称性: 如果<code>v</code>和<code>w</code>是强连通的,那么<code>w</code>和<code>v</code>也是强连通的.</li>
</ul>
<ul>
<li>传递性: 如果<code>v</code>和<code>w</code>是强连通的且<code>w</code>和<code>x</code>也是强连通的,那么<code>v</code>和<code>x</code>也是强连通的.</li>
</ul>
<p><code>强连通性</code>将所有<code>顶点</code>分为了一些等价类,每个等价类都是由相互为强连通的<code>顶点</code>的最大子集组成的.这些子集称为<code>强连通分量</code>,它的定义是基于顶点的,而非边.</p>
<p>一个含有<code>V</code>个顶点的<code>有向图</code>含有<code>1 ~ V</code>个<code>强连通分量</code>.一个<code>强连通图</code>只含有一个<code>强连通分量</code>,而一个<code>有向无环图</code>中则含有<code>V</code>个<code>强连通分量</code>.</p>
<h4 id="Kosaraju算法"><a href="#Kosaraju算法" class="headerlink" title="Kosaraju算法"></a>Kosaraju算法</h4><hr>
<p><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm">Kosaraju</a>算法是用于枚举图中每个<code>强连通分量</code>内的所有顶点,它主要有以下步骤: </p>
<ul>
<li>在给定一幅<code>有向图</code>$G$中,取得它的反向图$G^R$.</li>
</ul>
<ul>
<li>利用<code>深度优先搜索</code>得到$G^R$的逆后序排列.</li>
</ul>
<ul>
<li>按照上述逆后序的序列进行<code>深度优先搜索</code></li>
</ul>
<ul>
<li>同一个<code>深度优先搜索</code>递归子程序中访问的所有<code>顶点</code>都在同一个<code>强连通分量</code>内.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">KosarajuSharirSCC</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Digraph digraph;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// marked[v] = has vertex v been visited?</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// id[v] = id of strong component containing v</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] id;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// number of strongly-connected components</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> count;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">KosarajuSharirSCC</span><span class="params">(Digraph digraph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.digraph = digraph;</span><br><span class="line">        <span class="keyword">int</span> vertex = digraph.vertex();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// compute reverse postorder of reverse graph</span></span><br><span class="line">        DepthFirstOrder depthFirstOrder = <span class="keyword">new</span> DepthFirstOrder(digraph.reverse());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// run DFS on G, using reverse postorder to guide calculation</span></span><br><span class="line">        marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        id = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : depthFirstOrder.reversePost()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) &#123;</span><br><span class="line">                dfs(v);</span><br><span class="line">                count++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// check that id[] gives strong components</span></span><br><span class="line">        <span class="function"><span class="keyword">assert</span> <span class="title">check</span><span class="params">(digraph)</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line">        id[v] = count;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : digraph.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w])</span><br><span class="line">                dfs(w);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">count</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">stronglyConnected</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        <span class="keyword">return</span> id[v] == id[w];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">id</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> id[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// does the id[] array contain the strongly connected components?</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">check</span><span class="params">(Digraph G)</span> </span>&#123;</span><br><span class="line">        TransitiveClosure tc = <span class="keyword">new</span> TransitiveClosure(G);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; G.vertex(); v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w = <span class="number">0</span>; w &lt; G.vertex(); w++) &#123;</span><br><span class="line">                <span class="keyword">if</span> (stronglyConnected(v, w) != (tc.reachable(v, w) &amp;&amp; tc.reachable(w, v)))</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="传递闭包"><a href="#传递闭包" class="headerlink" title="传递闭包"></a>传递闭包</h3><hr>
<p><img src="http://algs4.cs.princeton.edu/42digraph/images/transitive-closure.png"></p>
<p>在一幅有向图<code>G</code>中,<code>传递闭包</code>是由相同的一组<code>顶点</code>组成的另一幅<code>有向图</code>,在<code>传递闭包</code>中存在一条从<code>v</code>指向<code>w</code>的边且仅当在<code>G</code>中<code>w</code>是从<code>v</code>可达的.</p>
<p>由于<code>有向图</code>的性质,每个<code>顶点</code>对于自己都是可达的,所以<code>传递闭包</code>会含有<code>V</code>个自环.</p>
<p>通常将<code>传递闭包</code>表示为一个布尔值矩阵,其中<code>v</code>行<code>w</code>列的值为<code>true</code>代表当且仅当<code>w</code>是从<code>v</code>可达的.</p>
<p><code>传递闭包</code>不适合于处理<code>大型有向图</code>,因为构造函数所需的空间与$V^2$成正比,所需的时间和$V(V+E)$成正比.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TransitiveClosure</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> DirectedDFS[] tc;  <span class="comment">// tc[v] = reachable from v</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">TransitiveClosure</span><span class="params">(Digraph G)</span> </span>&#123;</span><br><span class="line">        tc = <span class="keyword">new</span> DirectedDFS[G.vertex()];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; G.vertex(); v++)</span><br><span class="line">            tc[v] = <span class="keyword">new</span> DirectedDFS(G, v);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">reachable</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        <span class="keyword">return</span> tc[v].marked(w);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// throw an IllegalArgumentException unless &#123;@code 0 &lt;= v &lt; V&#125;</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> V = tc.length;</span><br><span class="line">        <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= V)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (V - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/42digraph/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm">Kosaraju’s algorithm - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Transitive_closure">Transitive closure - Wikipedia</a></li>
</ul>
<h3 id="图的那点事儿"><a href="#图的那点事儿" class="headerlink" title="图的那点事儿"></a>图的那点事儿</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">图的那点事儿(1)-无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">图的那点事儿(2)-有向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">图的那点事儿(3)-加权无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">图的那点事儿(4)-加权有向图</a></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/19/2017-07-19-FaceMash/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/19/2017-07-19-FaceMash/" class="post-title-link" itemprop="url">电影<<社交网络>>中的"FaceMash"算法</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-19 18:00:00" itemprop="dateCreated datePublished" datetime="2017-07-19T18:00:00+08:00">2017-07-19</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Other/" itemprop="url" rel="index"><span itemprop="name">Other</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p><img src="https://img3.doubanio.com/view/photo/raw/public/p679478005.jpg"></p>
<blockquote>
<p>最近在看<a target="_blank" rel="noopener" href="https://movie.douban.com/subject/3205624/">&lt;&lt;社交网络&gt;&gt;</a>时,发现了一个用于投票排名的算法,自己折腾实现了一下.</p>
</blockquote>
<p>在影片中,卷西饰演的扎克伯格在被妹子甩了之后(其实是他自己直男癌),一气之下黑了附近女生宿舍的照片数据库打算做一个<code>FaceMash</code>(通过投票的方式来选出漂亮的女生,同时它也是<code>Facebook</code>的前身,后来这个网站由于流量太大,搞崩了哈佛大学的网络而被强行关闭了),并使用了他的好基友爱德华多用于计算国际象棋排名的算法.</p>
<p><strong>这是一部很好看的电影,如果没有看过我强烈推荐去看一看.</strong></p>
<h3 id="公式"><a href="#公式" class="headerlink" title="公式"></a>公式</h3><hr>
<p><img src="http://wx4.sinaimg.cn/large/63503acbly1fhpbwf3qy2j20vx0hx74u.jpg"></p>
<p>这个算法是用来计算<code>期望胜率</code>的,但影片中其实写的是错误的,正确的公式应该为: </p>
<p>$$E_a = \frac{1} {1 + 10 ^ {(R_b - R_a) / 400}}$$</p>
<ul>
<li>$E_a$就是<code>a</code>的期望胜率.</li>
</ul>
<ul>
<li>$R_b,R_a$是<code>b</code>与<code>a</code>的<code>Rank</code>分数.</li>
</ul>
<ul>
<li>当$R_a,R_b$都相同时,它们的<code>期望胜率</code>都为<code>0.5</code>,即$E_a = \frac{1} {1+10^0} = 0.5$.</li>
</ul>
<p>电影中只给出了计算<code>期望胜率</code>的算法,但我们还需要一个计算新的<code>Rank</code>分数的算法,公式如下: </p>
<p>$$R_n = R_o + K(W - E)$$</p>
<ul>
<li>$R_n$代表新的<code>Rank</code>,$R_o$自然就是旧的<code>Rank</code>了.</li>
</ul>
<ul>
<li><code>K</code>为一个定值,我把它设为<code>10</code>.</li>
</ul>
<ul>
<li><code>W</code>是<code>胜负值</code>,胜者为<code>1</code>,败者为<code>0</code>;<code>E</code>就是我们上面计算的<code>期望胜率</code>.</li>
</ul>
<h3 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h3><hr>
<p>有了这两个核心公式,我们就可以开始实现这个算法了,但在代码实现之前,我们先验证一下公式: </p>
<p>假设有两个女孩<code>A</code>与<code>B</code>,她们的基础<code>Rank</code>都为<code>1400</code>,通过上述的推论我们已经得知,<strong><code>当A</code>,<code>B</code>的分值相同时,她们的期望胜率都为0.5</strong>.</p>
<p>如果,我选择了<code>A</code>,则<code>A</code>的胜负值变为<code>1</code>,<code>B</code>的胜负值为<code>0</code>,然后我们套用公式2可以得出: </p>
<ul>
<li>$R_a = 1400 + 10 * (1 - 0.5) = 1405$</li>
</ul>
<ul>
<li>$R_b = 1400 + 10 * (0 - 0.5) = 1395$</li>
</ul>
<p>由于她们的分数不再相同,所以套用公式1计算现在的<code>期望胜率</code>: </p>
<ul>
<li>$R_a = \frac{1} {1 + 10 ^ {(1395 - 1405) / 400}} \approx 0.51439 $</li>
</ul>
<ul>
<li>$R_b = \frac{1} {1 + 10 ^ {(1405 - 1395) / 400}} \approx 0.48561$</li>
</ul>
<p>下面是我用<code>C</code>写的一个小程序,它初始化了两个”女孩”,然后根据输入来判断哪个胜出,并动态计算<code>Rank</code>与<code>期望胜率</code>.</p>
<p><img src="http://wx1.sinaimg.cn/mw690/63503acbly1fhpcccyw1bj20di0gcdg7.jpg"></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;math.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">char</span> *name;</span><br><span class="line">    <span class="keyword">int</span> rank;</span><br><span class="line">    <span class="keyword">double</span> expect_rate;</span><br><span class="line">&#125; girl;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> K = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">read_girl</span><span class="params">(girl g)</span> </span>&#123;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;Girl name: %s, rank: %d, expect_rate: %.5f\n&quot;</span>,g.name,g.rank,g.expect_rate);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">compute_expect_rate</span><span class="params">(girl *a,girl *b)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> a_rank = a-&gt;rank;</span><br><span class="line">    <span class="keyword">int</span> b_rank = b-&gt;rank;</span><br><span class="line">    <span class="comment">// expect rate formula</span></span><br><span class="line">    <span class="comment">// Ea = 1 / (1 + 10 ^ ((Rb-Ra) / 400))</span></span><br><span class="line">    <span class="keyword">double</span> a_rank_differ = (<span class="keyword">double</span>) (b_rank - a_rank) / <span class="number">400</span>;</span><br><span class="line">    <span class="keyword">double</span> a_rank_rate = <span class="built_in">pow</span>(<span class="number">10</span>,a_rank_differ);</span><br><span class="line">    a-&gt;expect_rate = <span class="number">1</span> / (<span class="number">1</span> + a_rank_rate);</span><br><span class="line">    <span class="comment">// Eb = 1 / (1 + 10 ^ ((Ra-Rb) / 400))</span></span><br><span class="line">    <span class="keyword">double</span> b_rank_differ = (<span class="keyword">double</span>) (a_rank - b_rank) / <span class="number">400</span>;</span><br><span class="line">    <span class="keyword">double</span> b_rank_rate = <span class="built_in">pow</span>(<span class="number">10</span>,b_rank_differ);</span><br><span class="line">    b-&gt;expect_rate = <span class="number">1</span> / (<span class="number">1</span> + b_rank_rate);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// new rank formula: Rn = Ro + K(W - E)</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">compute_rank</span><span class="params">(girl *a,girl *b,<span class="keyword">int</span> a_win_rate,<span class="keyword">int</span> b_win_rate)</span> </span>&#123;</span><br><span class="line">    a-&gt;rank = a-&gt;rank + K * (a_win_rate - a-&gt;expect_rate);</span><br><span class="line">    b-&gt;rank = b-&gt;rank + K * (b_win_rate - b-&gt;expect_rate);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">(<span class="keyword">int</span> argc,<span class="keyword">char</span> *argv[])</span> </span>&#123;</span><br><span class="line">    <span class="keyword">char</span> a_girl_name[<span class="number">20</span>];</span><br><span class="line">    <span class="keyword">char</span> b_girl_name[<span class="number">20</span>];</span><br><span class="line"></span><br><span class="line">    girl a = &#123;.name = <span class="string">&quot;A Gril&quot;</span>,.rank = <span class="number">1400</span>&#125;;</span><br><span class="line">    girl b = &#123;.name = <span class="string">&quot;B Gril&quot;</span>,.rank = <span class="number">1400</span>&#125;;</span><br><span class="line"></span><br><span class="line">    compute_expect_rate(&amp;a,&amp;b);</span><br><span class="line"></span><br><span class="line">    read_girl(a);</span><br><span class="line">    read_girl(b);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">char</span> choice[<span class="number">2</span>];</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Choice A or B?\n&quot;</span>);</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%s&quot;</span>,choice);</span><br><span class="line">        <span class="keyword">if</span> (choice[<span class="number">0</span>] == <span class="string">&#x27;A&#x27;</span>) &#123;</span><br><span class="line">            compute_rank(&amp;a,&amp;b,<span class="number">1</span>,<span class="number">0</span>);</span><br><span class="line">            compute_expect_rate(&amp;a,&amp;b);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (choice[<span class="number">0</span>] == <span class="string">&#x27;B&#x27;</span>) &#123;</span><br><span class="line">            compute_rank(&amp;a,&amp;b,<span class="number">0</span>,<span class="number">1</span>);</span><br><span class="line">            compute_expect_rate(&amp;a,&amp;b);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;Invalid choice!\n&quot;</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        read_girl(a);</span><br><span class="line">        read_girl(b);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/" class="post-title-link" itemprop="url">图的那点事儿(1)-无向图</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-07-18 11:00:00" itemprop="dateCreated datePublished" datetime="2017-07-18T11:00:00+08:00">2017-07-18</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/Graph/" itemprop="url" rel="index"><span itemprop="name">Graph</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <p>在数学中,一个<code>图(Graph)</code>是表示物件与物件之间关系的方法,是<code>图论</code>的基本研究对象.一个图是由<code>顶点(Vertex)</code>与连接这些<code>顶点</code>的<code>边(Edge)</code>组成的.</p>
<p><code>图论</code>作为数学领域中的一个重要分支已经有数百年的历史了.人们发现了图的许多重要而实用的性质,发明了许多重要的算法,给你一个<code>图(Graph)</code>你可以联想到许多问题: 两个<code>顶点</code>之间是否存在一条链接?如果存在,两个<code>顶点</code>之间最短的连接又是哪一条?….</p>
<p>在生活中,到处都可以发现<code>图论</code>的应用: </p>
<ul>
<li>地图: 在使用地图中,我们经常会想知道”从xx到xx的最短路线”这样的问题,要回答这些问题,就需要把地图抽象成一个<code>图(Graph)</code>,十字路口就是<code>顶点</code>,公路就是<code>边</code>.</li>
</ul>
<ul>
<li>互联网: 整个互联网其实就是一张<code>图</code>,它的<code>顶点</code>为网页,<code>边</code>为超链接.而<code>图论</code>可以帮助我们在网络上定位信息.</li>
</ul>
<ul>
<li>任务调度: 当一些任务拥有优先级限制且需要满足前置条件时,如何在满足条件的情况下用最少的时间完成就需要用到<code>图论</code>.</li>
</ul>
<ul>
<li>社交网络: 在使用社交网站时,你就是一个<code>顶点</code>,你和你的朋友建立的关系则是<code>边</code>.分析这些社交网络的性质也是<code>图论</code>的一个重要应用.</li>
</ul>
<p><strong><code>图</code>就是由一组<code>顶点</code>和一组能够将两个<code>顶点</code>相连的<code>边</code>组成的.</strong></p>
<h3 id="基本术语"><a href="#基本术语" class="headerlink" title="基本术语"></a>基本术语</h3><hr>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/graph-anatomy.png" alt="图中的元素"></p>
<ul>
<li>相邻: 当两个<code>顶点</code>通过一条<code>边</code>相连接时,这两个<code>顶点</code>即为相邻的(也可以说这条<code>边</code>依附于这两个<code>顶点</code>).</li>
</ul>
<ul>
<li>度数: 某个<code>顶点</code>的<code>度数</code>即为依附于它的<code>边</code>的总数.</li>
</ul>
<ul>
<li>阶: <code>图G</code>中的<code>顶点集合V</code>的大小称为<code>G</code>的阶.</li>
</ul>
<ul>
<li>自环: 一条连接一个<code>顶点</code>和其自身的<code>边</code>.</li>
</ul>
<ul>
<li><p>平行边: 连接同一对<code>顶点</code>的两条<code>边</code>称为平行边.</p>
</li>
<li><p>桥: 如果去掉一条<code>边</code>会使整个<code>图</code>变成<code>非连通图</code>,则该<code>边</code>称为桥.</p>
</li>
<li><p>路径: 当<code>顶点v</code>到<code>顶点w</code>是连通时,我们用<code>v-&gt;x-&gt;y-&gt;w</code>为一条<code>v</code>到<code>w</code>的路径,用<code>v-&gt;x-&gt;y-&gt;v</code>表示一条环.</p>
</li>
</ul>
<ul>
<li>子图: 也称作<code>连通分量</code>,它由一张<code>图</code>的所有边的一个子集组成的<code>图</code>(以及依附的所有顶点).</li>
</ul>
<ul>
<li>连通图: <code>连通图</code>是一个整体,而<code>非连通图</code>则包含两个或多个<code>连通分量</code>.</li>
</ul>
<ul>
<li>稀疏图: 如果一张图中不同的<code>边</code>的数量在<code>顶点</code>总数<code>V</code>的一个小的常数倍内,那么该图就为稀疏图,否则为稠密图.</li>
</ul>
<ul>
<li>简单图与多重图: 含有<code>平行边</code>与<code>自环</code>的图称为<code>多重图</code>,而不含有<code>平行边</code>和<code>自环</code>的图称为<code>简单图</code>.</li>
</ul>
<h3 id="树"><a href="#树" class="headerlink" title="树"></a>树</h3><hr>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/tree.png" alt="树"></p>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/forest.png" alt="森林"></p>
<p>树是一张<code>无环连通图</code>,互不相连的树组成的集合称为森林.<code>连通图</code>的<code>生成树</code>是它的一张子图,它含有图中的所有顶点且是一棵树.图的<code>生成树森林</code>是它的所有<code>连通分量</code>的<code>生成树</code>的集合.</p>
<p>图<code>G</code>只要满足以下性质,那么它就是一棵树: </p>
<ul>
<li><code>G</code>有<code>V-1</code>条边且不含有环.</li>
</ul>
<ul>
<li><code>G</code>有<code>V-1</code>条边且是连通的.</li>
</ul>
<ul>
<li><code>G</code>是连通的,但删除任意一条边都会使它不再连通.</li>
</ul>
<ul>
<li><code>G</code>是无环图,但添加任意一条边都会产生一条环.</li>
</ul>
<ul>
<li><code>G</code>中的任意一对顶点之间仅存在一条简单路径(一条没有重复顶点的路径).</li>
</ul>
<h3 id="二分图"><a href="#二分图" class="headerlink" title="二分图"></a>二分图</h3><hr>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Simple-bipartite-graph.svg/600px-Simple-bipartite-graph.svg.png" alt="U和V就是两个顶点集合"></p>
<p><code>二分图</code>是一种能够将所有<code>顶点</code>分为两部分的图,其中<code>图</code>的每条边所连接的两个<code>顶点</code>都分别属于不同的部分.</p>
<p>设<code>G = (V,E)</code>为一张<code>无向图</code>,如果顶点<code>V</code>可以分割为两个互不相交的子集<code>(U,V)</code>,且图中的每条边<code>(x,y)</code>所关联的两个顶点<code>x</code>,<code>y</code>分别属于这两个不同的顶点集合<code>(x in U , y in V)</code>,则<code>G</code>为<code>二分图</code>.</p>
<p>也可以将<code>(U,V)</code>当做一张<code>着色图</code>: <code>U</code>中的所有顶点为蓝色,<code>V</code>中的所有顶点为绿色,每条边所关联的两个<code>顶点</code>颜色不同.</p>
<h3 id="无向图"><a href="#无向图" class="headerlink" title="无向图"></a>无向图</h3><hr>
<p><code>无向图</code>是一种最简单的图模型,它的每条边都没有方向.</p>
<h4 id="图的表示方法"><a href="#图的表示方法" class="headerlink" title="图的表示方法"></a>图的表示方法</h4><hr>
<p>实现一张<code>图</code>的<code>API</code>需要满足以下两个要求:</p>
<ol>
<li>必须为可能在应用中碰到的各种类型的<code>图</code>预留出足够的空间.</li>
</ol>
<ol start="2">
<li><code>图</code>的实现一定要足够快(因为这是所有处理<code>图</code>的算法的基础结构).</li>
</ol>
<p>有以下三种数据结构能够用来表示一张图:</p>
<ul>
<li>邻接矩阵: 使用一个<code>V * V</code>的布尔矩阵.当顶点<code>v</code>和顶点<code>w</code>之间有相连接的<code>边</code>时,将<code>v</code>行<code>w</code>列的元素设为<code>true</code>,否则为<code>false</code>.这种方法不符合第一个条件,当<code>图</code>的顶点非常多时,邻接矩阵所需的空间将会非常大.且它无法表示平行边.</li>
</ul>
<ul>
<li>边的数组: 使用一个<code>Edge</code>类,它含有两个<code>int</code>成员变量来表示所依附的顶点.这种方法简单直接但不满足第二个条件(要实现查询邻接点的函数需要检查图中的所有边).</li>
</ul>
<ul>
<li>邻接表数组: <strong>使用一个<code>顶点</code>为索引的<code>链表数组</code>,其中的每个元素都是和该<code>顶点</code>相邻的顶点列表(邻接点)</strong>.这种方法同时满足了两个条件,我们会使用这种方法来实现<code>图</code>的数据结构.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/adjacency-lists.png" alt="邻接表数组"></p>
<h4 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">Iterable&lt;Integer&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">degree</span><span class="params">(<span class="keyword">int</span> v)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="function">String <span class="title">toString</span><span class="params">()</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UndirectedGraph</span> <span class="keyword">implements</span> <span class="title">Graph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String NEW_LINE_SEPARATOR = System.getProperty(<span class="string">&quot;line.separator&quot;</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> vertex; <span class="comment">// 顶点</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> edge; <span class="comment">// 边</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Bag&lt;Integer&gt;[] adjacent; <span class="comment">// 邻接表数组,Bag是一个没有实现删除操作的Stack</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UndirectedGraph</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        checkVertex(vertex);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.vertex = vertex;</span><br><span class="line">        <span class="keyword">this</span>.edge = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.adjacent = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            adjacent[v] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 读取一个文件并初始化为无向图</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UndirectedGraph</span><span class="params">(Scanner scanner)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (scanner == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Specified input stream must not null!&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">			<span class="comment">// 文件的第一行为顶点数</span></span><br><span class="line">            <span class="keyword">this</span>.vertex = scanner.nextInt();</span><br><span class="line">            checkVertex(<span class="keyword">this</span>.vertex);</span><br><span class="line">			<span class="comment">// 文件的第二行为边数</span></span><br><span class="line">            <span class="keyword">int</span> edge = scanner.nextInt();</span><br><span class="line">            checkEdge(<span class="keyword">this</span>.edge);</span><br><span class="line">            <span class="keyword">this</span>.adjacent = (Bag&lt;Integer&gt;[]) <span class="keyword">new</span> Bag[<span class="keyword">this</span>.vertex];</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; <span class="keyword">this</span>.vertex; v++)</span><br><span class="line">                adjacent[v] = <span class="keyword">new</span> Bag&lt;Integer&gt;();</span><br><span class="line">			</span><br><span class="line">			<span class="comment">// 文件的剩余行为相连的顶点对 </span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; edge; i++) &#123;</span><br><span class="line">                <span class="keyword">int</span> v = scanner.nextInt();</span><br><span class="line">                <span class="keyword">int</span> w = scanner.nextInt();</span><br><span class="line">                addEdge(v, w);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NoSuchElementException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Invalid input format in Undirected Graph constructor&quot;</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UndirectedGraph</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(graph.vertex());</span><br><span class="line">        <span class="keyword">this</span>.edge = graph.edge();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; <span class="keyword">this</span>.vertex; v++) &#123;</span><br><span class="line">            <span class="comment">// reverse so that adjacency list is in same order as original</span></span><br><span class="line">            Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;Integer&gt;();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v))</span><br><span class="line">                stack.push(w);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : stack)</span><br><span class="line">                adjacent[v].add(w);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">checkVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt;= <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of vertices must be positive number!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">checkEdge</span><span class="params">(<span class="keyword">int</span> edge)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (edge &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Number of edges must be positive number!&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">vertex</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> vertex;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">edge</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> edge;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 添加一条连接v和w的边,由于是无向图所以这条边会出现两次</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addEdge</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        adjacent[v].add(w);</span><br><span class="line">        adjacent[w].add(v);</span><br><span class="line">        edge++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">adj</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adjacent[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">degree</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> adjacent[v].size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt; <span class="number">0</span> || vertex &gt;= <span class="keyword">this</span>.vertex)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertex &quot;</span> + vertex + <span class="string">&quot; is not between 0 and &quot;</span> + (<span class="keyword">this</span>.vertex - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">        sb.append(<span class="string">&quot;Vertices: &quot;</span>).append(vertex).append(<span class="string">&quot; Edges: &quot;</span>).append(edge).append(NEW_LINE_SEPARATOR);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            sb.append(v).append(<span class="string">&quot;: &quot;</span>);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : adjacent[v])</span><br><span class="line">                sb.append(w).append(<span class="string">&quot; &quot;</span>);</span><br><span class="line">            sb.append(NEW_LINE_SEPARATOR);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> FileNotFoundException </span>&#123;</span><br><span class="line">        InputStream inputStream =</span><br><span class="line">                UndirectedGraph.class.getResourceAsStream(<span class="string">&quot;/graph_file/C4_1_UndirectedGraphs/&quot;</span> + args[<span class="number">0</span>]);</span><br><span class="line">        Scanner scanner = <span class="keyword">new</span> Scanner(inputStream, <span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        Graph graph = <span class="keyword">new</span> UndirectedGraph(scanner);</span><br><span class="line">        System.out.println(graph);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的这个实现拥有以下特点: </p>
<ul>
<li>使用的空间和<code>V + E</code>成正比.</li>
</ul>
<ul>
<li>添加一条边所需的时间为常数.</li>
</ul>
<ul>
<li>遍历顶点<code>v</code>的所有邻接点所需的时间和<code>v</code>的度数成正比(处理每个邻接点所需的时间为常数).</li>
</ul>
<ul>
<li>边的插入顺序决定了邻接表中顶点的出现顺序.</li>
</ul>
<ul>
<li>支持平行边与自环.</li>
</ul>
<ul>
<li>不支持添加或删除顶点的操作(如果想要支持这些操作需要使用一个<code>符号表</code>来代替由顶点索引构成的数组).</li>
</ul>
<ul>
<li>不支持删除边的操作(如果想要支持这个操作需要使用一个<code>SET</code>来代替<code>Bag</code>来实现邻接表,这种方法也叫<code>邻接集</code>).</li>
</ul>
<p>每种<code>图</code>实现的性能复杂度如下表: </p>
<table>
<thead>
<tr>
<th>数据结构</th>
<th>所需空间</th>
<th>添加一条边v - w</th>
<th>检查w和v是否相邻</th>
<th>遍历v的所有邻接点</th>
</tr>
</thead>
<tbody><tr>
<td>边的数组</td>
<td>E</td>
<td>1</td>
<td>E</td>
<td>E</td>
</tr>
<tr>
<td>邻接矩阵</td>
<td>V^2</td>
<td>1</td>
<td>1</td>
<td>V</td>
</tr>
<tr>
<td>邻接表</td>
<td>E+V</td>
<td>1</td>
<td>degree(V)</td>
<td>degree(V)</td>
</tr>
<tr>
<td>邻接集</td>
<td>E+V</td>
<td>logV</td>
<td>logV</td>
<td>logV+degree(V)</td>
</tr>
</tbody></table>
<blockquote>
<p>本文中的所有完整代码可以到我的<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/algs4-study/tree/master/src/main/java/chapter4_graphs/C4_1_UndirectedGraphs">GitHub</a>中查看.</p>
</blockquote>
<h3 id="深度优先搜索"><a href="#深度优先搜索" class="headerlink" title="深度优先搜索"></a>深度优先搜索</h3><hr>
<p>处理<code>图</code>的基本问题: <code>v 到 w是否是相连的?</code>. <code>深度优先搜索</code>就是用于解决这样问题的,它会<strong>沿着<code>图</code>的<code>边</code>寻找和<code>起点</code>连通的所有<code>顶点</code>.</strong></p>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/search-api.png" alt="搜索的基本API"></p>
<p>如其名一样,<code>深度优先搜素</code>就是沿着<code>图</code>的<code>深度</code>来遍历<code>顶点</code>,它类似于走迷宫,会沿着一条路径一直走,直到走到尽头时再回退到上一个路口.为了防止迷路,还需要使用工具来标记已走过的路口(在我们的代码实现中使用一个布尔数组来进行标记).</p>
<h4 id="递归实现"><a href="#递归实现" class="headerlink" title="递归实现"></a>递归实现</h4><hr>
<p>使用递归方法来实现<code>深度优先搜索</code>会很简洁,当遇到一个<code>顶点</code>时:</p>
<ul>
<li>将它标记为已访问.</li>
</ul>
<ul>
<li>递归地访问它的所有没有被访问过的邻接点.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DepthFirstSearch</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked; <span class="comment">// 标记已访问过的顶点</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> count;  <span class="comment">// 记录起点连通的顶点数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DepthFirstSearch</span><span class="params">(Graph graph, <span class="keyword">int</span> originPoint)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">this</span>.count = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[graph.vertex()];</span><br><span class="line">        validateVertex(originPoint);</span><br><span class="line">		<span class="comment">// 从起点开始进行深度优先搜索</span></span><br><span class="line">        depthSearch(originPoint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">count</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">marked</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> marked[vertex];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">depthSearch</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">        count++;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> adj : graph.adj(vertex)) &#123;</span><br><span class="line">			<span class="comment">// 遍历邻接点,如果未访问则递归调用</span></span><br><span class="line">            <span class="keyword">if</span> (!marked[adj])</span><br><span class="line">                depthSearch(adj);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> length = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt; <span class="number">0</span> || vertex &gt;= length)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertex &quot;</span> + vertex + <span class="string">&quot; is not between 0 and &quot;</span> + (length - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="非递归实现"><a href="#非递归实现" class="headerlink" title="非递归实现"></a>非递归实现</h4><hr>
<p>如果是了解<code>JVM</code>中函数调用的小伙伴们应该知道,函数都会封装成一个个<code>栈帧</code>然后压入<code>虚拟机栈</code>,上述的递归实现其实就是在隐式的使用到了<code>栈</code>,要想实现非递归,我们需要显式使用<code>栈</code>这个数据结构.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NonrecursiveDFS</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked; </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Iterator&lt;Integer&gt;[] adj;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">NonrecursiveDFS</span><span class="params">(Graph graph, <span class="keyword">int</span> originPoint)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        validateVertex(originPoint);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 取出所有顶点的邻接表迭代器</span></span><br><span class="line">        adj = (Iterator&lt;Integer&gt;[]) <span class="keyword">new</span> Iterator[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++)</span><br><span class="line">            adj[v] = graph.adj(v).iterator();</span><br><span class="line"></span><br><span class="line">        dfs(originPoint);</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> originPoint)</span> </span>&#123;</span><br><span class="line">        Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">		<span class="comment">// 标记起点并放入栈</span></span><br><span class="line">        marked[originPoint] = <span class="keyword">true</span>;</span><br><span class="line">        stack.push(originPoint);</span><br><span class="line">		</span><br><span class="line">        <span class="keyword">while</span> (!stack.isEmpty()) &#123;</span><br><span class="line">            Integer v = stack.peek();</span><br><span class="line">			<span class="comment">// 遍历栈顶顶点的邻接点</span></span><br><span class="line">            <span class="keyword">if</span> (adj[v].hasNext()) &#123;</span><br><span class="line">                <span class="keyword">int</span> w = adj[v].next();</span><br><span class="line">				<span class="comment">// 如果未被访问,进行标记并放入栈中</span></span><br><span class="line">                <span class="keyword">if</span> (!marked[w]) &#123;</span><br><span class="line">                    marked[w] = <span class="keyword">true</span>;</span><br><span class="line">                    stack.push(w);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				<span class="comment">// 当栈顶顶点的所有邻接点已经遍历完时,弹出栈</span></span><br><span class="line">                stack.pop();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="寻找路径"><a href="#寻找路径" class="headerlink" title="寻找路径"></a>寻找路径</h3><hr>
<p>在<code>图</code>的应用中,找出<code>v-w</code>的可达路径也是常见的问题之一.</p>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/paths-api.png" alt="单点路径API"></p>
<p>我们基于<code>深度优先搜索</code>实现寻找路径,并添加一个<code>edgeTo[]</code>整形数组来记录路径.例如,在由边<code>v-w</code>第一次访问任意<code>w</code>时,将<code>edgeTo[w]</code>设为<code>v</code>来记录这条路径(<code>v-w</code>是从起点到<code>w</code>的路径上最后一条已知的边).这样搜索到的路径就是一颗以起点为根的树,<code>edgeTo[]</code>是一颗由父链接表示的树.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DepthFirstPaths</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked; </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] edgeTo; <span class="comment">// 用于记录路径</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> originPoint;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DepthFirstPaths</span><span class="params">(Graph graph, <span class="keyword">int</span> originPoint)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">this</span>.originPoint = originPoint;</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        validateVertex(originPoint);</span><br><span class="line">        dfs(originPoint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasPathTo</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> marked[vertex];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">pathTo</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line"></span><br><span class="line">        Stack&lt;Integer&gt; stack = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">		<span class="comment">// 从指定顶点处向上遍历路径(直到起点)</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> x = vertex; x != originPoint; x = edgeTo[x])</span><br><span class="line">            stack.push(x);</span><br><span class="line">        stack.push(originPoint);</span><br><span class="line">        <span class="keyword">return</span> stack;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> adj : graph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[adj]) &#123;</span><br><span class="line">                marked[adj] = <span class="keyword">true</span>;</span><br><span class="line">				<span class="comment">// edgeTo[w] = v,记录了父链接</span></span><br><span class="line">                edgeTo[adj] = vertex;</span><br><span class="line">                dfs(adj);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="广度优先搜索"><a href="#广度优先搜索" class="headerlink" title="广度优先搜索"></a>广度优先搜索</h3><hr>
<p>对于寻找一条最短路径,<code>深度优先搜索</code>没有什么作为,因为它遍历整个图的顺序和找出最短路径的目标没有任何关系.这种问题就需要用到<code>广度优先搜索</code>.</p>
<p><code>广度优先搜索</code>是沿着宽度来进行搜索的.例如,要找到<code>s</code>到<code>v</code>的最短路径,<strong>从<code>s</code>开始,在所有由一条边就可以到达的<code>顶点</code>中寻找<code>v</code>,如果找不到就继续在与<code>s</code>距离两条边的所有顶点中寻找<code>v</code>,以此类推</strong>.</p>
<p>如果说<code>深度优先搜索</code>是一个人在走迷宫,那么<code>广度优先搜索</code>就是一群人一起朝着各个方向去走迷宫.</p>
<p>在<code>广度优先搜索</code>中,我们使用一个<code>队列</code>来保存所有已被标记过但<code>邻接表</code>还未被检查过的<code>顶点</code>.先将<code>起点</code>放入<code>队列</code>,然后重复以下步骤直到<code>队列</code>为空:</p>
<ul>
<li>取出<code>队列</code>中的下一个<code>顶点</code>并标记.</li>
</ul>
<ul>
<li>将它相邻的所有未被标记过的<code>顶点</code>加入队列.</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BreadthFirstPaths</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> INFINITY = Integer.MAX_VALUE;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked; </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] edgeTo;      </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] distTo;      <span class="comment">// 记录路径中经过的顶点数,起点为0,需要全部初始化为无穷大</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BreadthFirstPaths</span><span class="params">(Graph graph, <span class="keyword">int</span> originPoint)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        distTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">            distTo[i] = INFINITY;</span><br><span class="line">        validateVertex(originPoint);</span><br><span class="line">        bfs(originPoint);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 以一组顶点为起点</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BreadthFirstPaths</span><span class="params">(Graph graph, Iterable&lt;Integer&gt; sources)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.distTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; vertex; i++)</span><br><span class="line">            distTo[i] = INFINITY;</span><br><span class="line">        validateVertices(sources);</span><br><span class="line">        bfs(sources);</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasPathTo</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> marked[vertex];</span><br><span class="line">    &#125;</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">distTo</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> distTo[vertex];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">pathTo</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line"></span><br><span class="line">        Stack&lt;Integer&gt; path = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">        <span class="keyword">int</span> x;</span><br><span class="line">		<span class="comment">// 这里使用distTo[x] != 0来判断是否为起点</span></span><br><span class="line">        <span class="keyword">for</span> (x = vertex; distTo[x] != <span class="number">0</span>; x = edgeTo[x])</span><br><span class="line">            path.push(x);</span><br><span class="line">        path.push(x);</span><br><span class="line">        <span class="keyword">return</span> path;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">bfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        Queue&lt;Integer&gt; queue = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">        distTo[vertex] = <span class="number">0</span>;</span><br><span class="line">        queue.add(vertex);</span><br><span class="line"></span><br><span class="line">        searchAndMarkAdjacent(queue);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">bfs</span><span class="params">(Iterable&lt;Integer&gt; sources)</span> </span>&#123;</span><br><span class="line">        Queue&lt;Integer&gt; queue = <span class="keyword">new</span> ArrayDeque&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : sources) &#123;</span><br><span class="line">            marked[v] = <span class="keyword">true</span>;</span><br><span class="line">            distTo[v] = <span class="number">0</span>;</span><br><span class="line">            queue.add(v);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        searchAndMarkAdjacent(queue);</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">	<span class="comment">// 广度优先搜索</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">searchAndMarkAdjacent</span><span class="params">(Queue&lt;Integer&gt; queue)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">            Integer v = queue.remove();</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> adj : graph.adj(v)) &#123;</span><br><span class="line">				<span class="comment">// 将未标记过的邻接点加入队列并进行标记等操作</span></span><br><span class="line">                <span class="keyword">if</span> (!marked[adj]) &#123;</span><br><span class="line">                    marked[adj] = <span class="keyword">true</span>;</span><br><span class="line">                    edgeTo[adj] = v;</span><br><span class="line">                    distTo[adj] = distTo[v] + <span class="number">1</span>;</span><br><span class="line">                    queue.add(adj);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertex</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> length = marked.length;</span><br><span class="line">        <span class="keyword">if</span> (vertex &lt; <span class="number">0</span> || vertex &gt;= length)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertex &quot;</span> + vertex + <span class="string">&quot; is not between 0 and &quot;</span> + (length - <span class="number">1</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateVertices</span><span class="params">(Iterable&lt;Integer&gt; vertices)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (vertices == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertices is null.&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> length = marked.length;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v : vertices) &#123;</span><br><span class="line">            <span class="keyword">if</span> (v &lt; <span class="number">0</span> || v &gt;= length)</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;Vertex &quot;</span> + v + <span class="string">&quot; is not between 0 and &quot;</span> + (length - <span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不管是<code>深度优先搜索</code>还是<code>广度优先搜索</code>,它们都是先将<code>起点</code>存入一个<code>数据结构</code>中,然后重复以下步骤直到<code>数据结构</code>被清空: </p>
<ul>
<li>取其中的下一个<code>顶点</code>并标记它.</li>
</ul>
<ul>
<li>将它的所有<code>相邻</code>而又未被标记的<code>顶点</code>放入<code>数据结构</code>中.</li>
</ul>
<p>这两种<code>算法</code>的<strong>不同之处仅在于从<code>数据结构</code>中获取下一个<code>顶点</code>的规则(对于<code>广度优先搜索</code>来说是最早加入的<code>顶点</code>,对于<code>深度优先搜索</code>来说是最晚加入的<code>顶点</code>)</strong>.</p>
<p><code>深度优先搜索</code>的方式是不断寻找离<code>起点</code>更远的<code>顶点</code>,直到碰见死胡同时才返回近处<code>顶点</code>.</p>
<p><code>广度优先搜索</code>的方式是先覆盖<code>起点</code>附近的<code>顶点</code>,只有当<code>邻接</code>的所有<code>顶点</code>都被访问过之后才继续前进.</p>
<p><code>深度优先搜素</code>的路径通常长且曲折,<code>广度优先搜索</code>的路径则短而直接.但不管是使用哪种<code>算法</code>,所有与<code>起点</code>连通的<code>顶点</code>和<code>边</code>都会被访问到.</p>
<h3 id="连通分量"><a href="#连通分量" class="headerlink" title="连通分量"></a>连通分量</h3><hr>
<p><code>深度优先搜索</code>的一个重要应用就是寻找出一幅<code>图</code>中的所有连通分量.</p>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/cc-api.png" alt="连通分量API"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConnectedComponent</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 顶点与它们所属的连通分量进行关联的数组</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] id;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 记录每个连通分量中有多少顶点的数组</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span>[] size;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 连通分量数</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> count;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ConnectedComponent</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.id = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.size = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[v]) &#123;</span><br><span class="line">                dfs(v);</span><br><span class="line">                count++; <span class="comment">// 一张连通图遍历完毕后,连通分量数 + 1</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">id</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> id[vertex];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">size</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        validateVertex(vertex);</span><br><span class="line">        <span class="keyword">return</span> size[id[vertex]];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">count</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> count;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 两个顶点是否处于一个连通分量中</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">connected</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> w)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        validateVertex(w);</span><br><span class="line">        <span class="keyword">return</span> id[v] == id[w];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> vertex)</span> </span>&#123;</span><br><span class="line">        marked[vertex] = <span class="keyword">true</span>;</span><br><span class="line">        id[vertex] = count;</span><br><span class="line">        size[count]++;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> adj : graph.adj(vertex)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[adj])</span><br><span class="line">                dfs(adj);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="检测环与双色问题"><a href="#检测环与双色问题" class="headerlink" title="检测环与双色问题"></a>检测环与双色问题</h3><hr>
<p><code>深度优先搜索</code>的应用远不于此,它还可以用来检测是否有环以及双色问题.</p>
<h4 id="检测环"><a href="#检测环" class="headerlink" title="检测环"></a>检测环</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Cyclic</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line">	</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span>[] marked</span><br><span class="line">	;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span>[] edgeTo;</span><br><span class="line">	<span class="comment">// 如果存在环则返回这条环路径</span></span><br><span class="line">    <span class="keyword">private</span> Stack&lt;Integer&gt; cyclic;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Cyclic</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">		<span class="comment">// 先检测是否有自环</span></span><br><span class="line">        <span class="keyword">if</span> (hasSelfLoop()) <span class="keyword">return</span>;</span><br><span class="line">		<span class="comment">// 再检测是否有平行边</span></span><br><span class="line">        <span class="keyword">if</span> (hasParallelEdges()) <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.edgeTo = <span class="keyword">new</span> <span class="keyword">int</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[v])</span><br><span class="line">                dfs(v, -<span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasCyclic</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cyclic != <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Iterable&lt;Integer&gt; <span class="title">cyclic</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cyclic;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">hasSelfLoop</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; graph.vertex(); v++) &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v)) &#123;</span><br><span class="line">				<span class="comment">// 如果v与w是同一个顶点,则代表有自环</span></span><br><span class="line">                <span class="keyword">if</span> (v == w) &#123;</span><br><span class="line">                    cyclic = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">                    cyclic.push(v);</span><br><span class="line">                    cyclic.push(v);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">hasParallelEdges</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line">        <span class="keyword">boolean</span>[] marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">		</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="comment">// check for parallel edges incident to v</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v)) &#123;</span><br><span class="line">                <span class="keyword">if</span> (marked[w]) &#123;</span><br><span class="line">                    cyclic = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">                    cyclic.push(v);</span><br><span class="line">                    cyclic.push(w);</span><br><span class="line">                    cyclic.push(v);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                marked[w] = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// reset so marked[v] = false for all v</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v))</span><br><span class="line">                marked[w] = <span class="keyword">false</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> v, <span class="keyword">int</span> u)</span> </span>&#123;</span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (cyclic != <span class="keyword">null</span>) <span class="keyword">return</span>;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w]) &#123;</span><br><span class="line">                edgeTo[w] = v;</span><br><span class="line">                dfs(w, v);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (w != u) &#123;</span><br><span class="line">                <span class="comment">// check for cycle (but disregard reverse of edge leading to v)</span></span><br><span class="line">                cyclic = <span class="keyword">new</span> Stack&lt;&gt;();</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> x = v; x != w; x = edgeTo[x])</span><br><span class="line">                    cyclic.push(x);</span><br><span class="line">                cyclic.push(w);</span><br><span class="line">                cyclic.push(v);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="检测双色"><a href="#检测双色" class="headerlink" title="检测双色"></a>检测双色</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TwoColor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] marked;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span>[] color;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> isTwoColorable = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">TwoColor</span><span class="params">(Graph graph)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.graph = graph;</span><br><span class="line">        <span class="keyword">int</span> vertex = graph.vertex();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">this</span>.marked = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line">        <span class="keyword">this</span>.color = <span class="keyword">new</span> <span class="keyword">boolean</span>[vertex];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> v = <span class="number">0</span>; v &lt; vertex; v++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[v])</span><br><span class="line">                dfs(v);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isBipartite</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> isTwoColorable;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">dfs</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        marked[v] = <span class="keyword">true</span>;</span><br><span class="line">		</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> w : graph.adj(v)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!marked[w]) &#123;</span><br><span class="line">				<span class="comment">// 将未被访问过的邻接点w设为v的反色</span></span><br><span class="line">                color[w] = !color[v];</span><br><span class="line">                dfs(w);</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (color[w] == color[v]) &#123;</span><br><span class="line">				<span class="comment">// 如果w已被访问且颜色与v相同,则代表这不是一张双色图</span></span><br><span class="line">                isTwoColorable = <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="符号图"><a href="#符号图" class="headerlink" title="符号图"></a>符号图</h3><hr>
<p>在很多应用中,是使用字符串而非整数来表示<code>顶点</code>的,为了适应这种需求,需要拥有以下性质的输入格式: </p>
<ul>
<li>顶点名是字符串.</li>
</ul>
<ul>
<li>用指定的分隔符来隔开顶点名</li>
</ul>
<ul>
<li>每一行都表示一组边的集合,每一条边都连接着这一行的第一个名称表示的顶点和其他名称所表示的顶点.</li>
</ul>
<ul>
<li>顶点集<code>V</code>与边集<code>E</code>都是隐式定义的.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/routes.png" alt="符号图的输入格式"></p>
<p>要实现<code>符号图</code>还需要借助以下数据结构: </p>
<ul>
<li>一个<code>符号表</code>,我这里使用的是<code>TreeMap</code>即<code>红黑树</code>,它的<code>Key</code>为<code>String</code>(顶点名),<code>Value</code>为<code>Integer</code>(顶点索引).</li>
</ul>
<ul>
<li>一个<code>字符串数组</code>,它用来与<code>符号表</code>作<code>反向索引</code>,保存每个<code>顶点</code>索引所对应的<code>顶点名</code>.</li>
</ul>
<ul>
<li>一个<code>Graph</code>对象,我们使用索引来生成这张<code>图</code>对象.</li>
</ul>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/symbol-graph-api.png" alt="符号图的API"></p>
<p><img src="http://algs4.cs.princeton.edu/41graph/images/symbol-graph.png" alt="需要用到的数据结构"></p>
<h4 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SymbolGraph</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> TreeMap&lt;String, Integer&gt; symbolTable; <span class="comment">// string -&gt; index</span></span><br><span class="line">    <span class="keyword">private</span> String[] keys; <span class="comment">// index -&gt; string</span></span><br><span class="line">    <span class="keyword">private</span> Graph graph;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SymbolGraph</span><span class="params">(String filename, String delimiter)</span> </span>&#123;</span><br><span class="line">        symbolTable = <span class="keyword">new</span> TreeMap&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 第一次读取文件</span></span><br><span class="line">        String filePath = <span class="string">&quot;/graph_file/C4_1_UndirectedGraphs/&quot;</span> + filename;</span><br><span class="line">        InputStream inputStream</span><br><span class="line">                = SymbolGraph.class.getResourceAsStream(filePath);</span><br><span class="line">        Scanner scanner = <span class="keyword">new</span> Scanner(inputStream, <span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 初始化符号表</span></span><br><span class="line">        <span class="keyword">while</span> (scanner.hasNextLine()) &#123;</span><br><span class="line">            String[] s = scanner.nextLine().split(delimiter);</span><br><span class="line">            <span class="keyword">for</span> (String key : s) &#123;</span><br><span class="line">                <span class="keyword">if</span> (!symbolTable.containsKey(key))</span><br><span class="line">                    symbolTable.put(key, symbolTable.size());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.printf(<span class="string">&quot;Done reading %s!\n&quot;</span>, filename);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 初始化反向索引</span></span><br><span class="line">        keys = <span class="keyword">new</span> String[symbolTable.size()];</span><br><span class="line">        <span class="keyword">for</span> (String name : symbolTable.keySet())</span><br><span class="line">            keys[symbolTable.get(name)] = name;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 第二次读取文件,并生成图</span></span><br><span class="line">        graph = <span class="keyword">new</span> UndirectedGraph(symbolTable.size());</span><br><span class="line">        Scanner create_graph_scanner = <span class="keyword">new</span> Scanner(SymbolGraph.class.getResourceAsStream(filePath));</span><br><span class="line">        <span class="keyword">while</span> (create_graph_scanner.hasNextLine()) &#123;</span><br><span class="line">            String[] s = create_graph_scanner.nextLine().split(delimiter);</span><br><span class="line">			<span class="comment">// 将第一行的第一个顶点与其他顶点相连</span></span><br><span class="line">            <span class="keyword">int</span> v = symbolTable.get(s[<span class="number">0</span>]);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; s.length; i++) &#123;</span><br><span class="line">                <span class="keyword">int</span> w = symbolTable.get(s[i]);</span><br><span class="line">                graph.addEdge(v, w);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">contains</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> symbolTable.containsKey(s);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">indexOf</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> symbolTable.get(s);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">nameOf</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span><br><span class="line">        validateVertex(v);</span><br><span class="line">        <span class="keyword">return</span> keys[v];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Graph <span class="title">graph</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> graph;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">Graph (discrete mathematics) - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Bipartite_graph">Bipartite graph - Wikipedia</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="http://algs4.cs.princeton.edu/41graph/">Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne</a></li>
</ul>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>
<h3 id="图的那点事儿"><a href="#图的那点事儿" class="headerlink" title="图的那点事儿"></a>图的那点事儿</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/18/2017-07-18-Graph_UndirectedGraph/">图的那点事儿(1)-无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/23/2017-07-23-Graph_DirectedGraphs/">图的那点事儿(2)-有向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/25/2017-07-25-Graph_WeightedUndirectedGraph/">图的那点事儿(3)-加权无向图</a></li>
</ul>
<ul>
<li><a target="_blank" rel="noopener" href="https://sylvanassun.github.io/2017/07/27/2017-07-27-Graph_WeightedDigraph">图的那点事儿(4)-加权有向图</a></li>
</ul>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/27/2017-06-27-DynamicProgramming/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/06/27/2017-06-27-DynamicProgramming/" class="post-title-link" itemprop="url">什么是动态规划?</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-27 18:00:00" itemprop="dateCreated datePublished" datetime="2017-06-27T18:00:00+08:00">2017-06-27</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/" itemprop="url" rel="index"><span itemprop="name">动态规划</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p>动态规划(Dynamic Programming)是一种分阶段求解决策问题的数学思想,它通过把原问题分解为简单的子问题来解决复杂问题.动态规划在很多领域都有着广泛的应用,例如管理学,经济学,数学,生物学.</p>
<p>动态规划适用于解决带有<code>最优子结构</code>和<code>子问题重叠</code>性质的问题.</p>
<ul>
<li><code>最优子结构</code> : 即是局部最优解能够决定全局最优解(也可以认为是问题可以被分解为子问题来解决),如果问题的最优解所包含的子问题的解也是最优的，我们就称该问题具有<code>最优子结构</code>性质.</li>
</ul>
<ul>
<li><code>子问题重叠</code> : 即是当使用递归进行自顶向下的求解时,<strong>每次产生的子问题不总是新的问题,而是已经被重复计算过的问题</strong>.动态规划利用了这种性质,使用一个集合将已经计算过的结果放入其中,当再次遇见重复的问题时,只需要从集合中取出对应的结果.</li>
</ul>
<h3 id="动态规划与分治算法的区别"><a href="#动态规划与分治算法的区别" class="headerlink" title="动态规划与分治算法的区别"></a>动态规划与分治算法的区别</h3><hr>
<p>相信了解过分治算法的同学会发现,动态规划与分治算法很相似,下面我们例举出一些它们的相同之处与不同之处.</p>
<h4 id="相同点"><a href="#相同点" class="headerlink" title="相同点"></a>相同点</h4><ul>
<li>分治算法与动态规划都是将一个复杂问题分解为简单的子问题.</li>
</ul>
<ul>
<li>分治算法与动态规划都只能解决带有<code>最优子结构</code>性质的问题.</li>
</ul>
<h4 id="不同点"><a href="#不同点" class="headerlink" title="不同点"></a>不同点</h4><ul>
<li>分治算法一般都是使用递归自顶向下实现,动态规划使用迭代自底向上实现或带有记忆功能的递归实现.</li>
</ul>
<ul>
<li>动态规划解决带有<code>子问题重叠</code>性质的问题效率更加高效.</li>
</ul>
<ul>
<li>分治算法分解的子问题是相对独立的.</li>
</ul>
<ul>
<li>动态规划分解的子问题是互相带有关联且有重叠的.</li>
</ul>
<h3 id="斐波那契数列"><a href="#斐波那契数列" class="headerlink" title="斐波那契数列"></a>斐波那契数列</h3><hr>
<p>斐波那契数列就很适合使用动态规划来求解,它在数学上是使用递归来定义的,公式为<code>F(n) = F(n-1) + F(n-2) </code>.</p>
<p><img src="http://wx3.sinaimg.cn/mw690/63503acbly1fgzut0a5nuj20lp08xq36.jpg" alt="斐波那契数列求解过程"></p>
<h4 id="普通递归实现"><a href="#普通递归实现" class="headerlink" title="普通递归实现"></a>普通递归实现</h4><p>一个最简单的实现如下.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">fibonacci</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &lt; <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">2</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> fibonacci(n - <span class="number">1</span>) + fibonacci(n - <span class="number">2</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但这种算法并不高效,它做了很多重复计算,它的时间复杂度为<code>O(2^n)</code>.</p>
<h4 id="动态规划递归实现"><a href="#动态规划递归实现" class="headerlink" title="动态规划递归实现"></a>动态规划递归实现</h4><p>使用动态规划来将重复计算的结果具有”记忆性”,就可以将时间复杂度降低为<code>O(n)</code>.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">fibonacci</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &lt; <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">2</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 判断当前n的结果是否已经被计算,如果map存在n则代表该结果已经计算过了</span></span><br><span class="line">	<span class="keyword">if</span> (map.containsKey(n))</span><br><span class="line">		<span class="keyword">return</span> map.get(n);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">int</span> value = fibonacci(n - <span class="number">1</span>) + fibonacci(n - <span class="number">2</span>);</span><br><span class="line">	map.put(n, value);</span><br><span class="line">	<span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>虽然降低了时间复杂度,但需要维护一个集合用于存放计算结果,导致空间复杂度提升了.</p>
<h4 id="动态规划迭代实现"><a href="#动态规划迭代实现" class="headerlink" title="动态规划迭代实现"></a>动态规划迭代实现</h4><p>通过观察斐波那契数列的规律,发现n只依赖于前2种状态,所以我们可以自底向上地迭代实现.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">fibonacci</span><span class="params">(<span class="keyword">int</span> n)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (n &lt; <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">1</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">if</span> (n == <span class="number">2</span>)</span><br><span class="line">		<span class="keyword">return</span> <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 使用变量a,b来保存上次迭代和上上次迭代的结果</span></span><br><span class="line">	<span class="keyword">int</span> a = <span class="number">1</span>;</span><br><span class="line">	<span class="keyword">int</span> b = <span class="number">2</span>;</span><br><span class="line">	<span class="keyword">int</span> temp = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">3</span>; i &lt;= n; i++) &#123;</span><br><span class="line">		temp = a + b;</span><br><span class="line">		a = b;</span><br><span class="line">		b = temp;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> temp;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样不仅时间复杂度得到了优化,也不需要额外的空间复杂度.</p>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><hr>
<ul>
<li><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92">Wikipedia</a></li>
</ul>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/16/2017-06-16-RedBlackTree/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/06/16/2017-06-16-RedBlackTree/" class="post-title-link" itemprop="url">红黑树那点事儿</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-16 18:00:00" itemprop="dateCreated datePublished" datetime="2017-06-16T18:00:00+08:00">2017-06-16</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" itemprop="url" rel="index"><span itemprop="name">数据结构</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/Tree/" itemprop="url" rel="index"><span itemprop="name">Tree</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p><code>红黑树</code>是一种<code>自平衡二叉查找树</code>,它相对于<code>二叉查找树</code>性能会更加高效(查找、删除、添加等操作需要<code>O(log n)</code>,其中<code>n</code>为树中元素的个数),但实现较为复杂(需要保持自身的平衡).</p>
<h3 id="性质"><a href="#性质" class="headerlink" title="性质"></a>性质</h3><hr>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_example.svg"></p>
<p><code>红黑树</code>与<code>二叉查找树</code>不同,它的节点多了一个颜色属性,每个节点非黑即红,这也是它名字的由来.</p>
<p><code>红黑树</code>的节点定义如以下代码: </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> RED = <span class="keyword">true</span>;</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">boolean</span> BLACK = <span class="keyword">false</span>;</span><br><span class="line"><span class="keyword">private</span> Node root;</span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Node</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> size = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> color = RED; <span class="comment">//颜色</span></span><br><span class="line">    <span class="keyword">private</span> Node parent, left, right;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> orderStatus = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">private</span> K key;</span><br><span class="line">    <span class="keyword">private</span> V value;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Node</span><span class="params">(K key, V value)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.key = key;</span><br><span class="line">        <span class="keyword">this</span>.value = value;</span><br><span class="line">        <span class="keyword">this</span>.size = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>完整的代码我已经放在了我的<code>Gist</code>中,<a target="_blank" rel="noopener" href="https://gist.github.com/SylvanasSun/147672912cc5bc6da27e15528542877f">点击查看完整代码</a>.</p>
<p><code>红黑树</code>需要保证以下性质: </p>
<ol>
<li>每个节点的颜色非黑即红.</li>
</ol>
<ol start="2">
<li><strong>根节点的颜色为黑色.</strong></li>
</ol>
<ol start="3">
<li>所有叶子节点都为黑色(即NIL节点).</li>
</ol>
<ol start="4">
<li><p><strong>每个红色节点的两个子节点都必须为黑色(不能有两个连续的红节点).</strong></p>
</li>
<li><p><strong>从任一节点到其叶子的所有简单路径包含相同数量的黑色节点.</strong></p>
</li>
</ol>
<h3 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h3><hr>
<p><code>红黑树</code>的查找操作与<code>二叉查找树</code>一致(因为查找不会影响树的结构),而插入与删除操作需要在最后对树进行调整.</p>
<p>我们将新的节点的颜色设为红色(如果设为黑色会使根节点到叶子的一条路径上多了一个黑节点,违反了性质5,这个是很难调整的).</p>
<p>现在我们假设新节点为<code>N</code>,它的父节点为<code>P</code>(且<code>P</code>为<code>G</code>的左节点,如果为右节点则与其操作互为镜像),祖父节点为<code>G</code>,叔叔节点为<code>U</code>.插入一个节点会有以下种情况.</p>
<h4 id="情况1"><a href="#情况1" class="headerlink" title="情况1"></a>情况1</h4><p><strong><code>N</code>位于根,它没有父节点与子节点,这时候只需要把它重新设置为黑色即可</strong>,无需其他调整.</p>
<h4 id="情况2"><a href="#情况2" class="headerlink" title="情况2"></a>情况2</h4><p><strong><code>P</code>的颜色为黑色</strong>,这种情况下保持了性质4(<code>N</code>只有两个叶子节点,它们都为黑色)与性质5(<code>N</code>是一个红色节点,不会对其造成影响)的有效,所以<strong>无需调整</strong>.</p>
<h4 id="情况3"><a href="#情况3" class="headerlink" title="情况3"></a>情况3</h4><p>如果<code>P</code>与<code>U</code>都为红色,我们可以将它们两个重新绘制为黑色,然后将<code>G</code>绘制为红色(保持性质5),最后再从<code>G</code>开始继续向上进行调整.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Red-black_tree_insert_case_3.png"></p>
<h4 id="情况4"><a href="#情况4" class="headerlink" title="情况4"></a>情况4</h4><p><strong><code>P</code>为红色,<code>U</code>为黑色,且<code>N</code>为<code>P</code>的左子节点,这种情况下,我们需要在<code>G</code>处进行一次<code>右旋转</code></strong>,结果满足了性质4与性质5,因为通过这三个节点中任何一个的所有路径以前都通过祖父节点<code>G</code>，现在它们都通过以前的父节点<code>P</code>.</p>
<p>关于旋转操作,可以查看这篇文章<a target="_blank" rel="noopener" href="http://sylvanassun.github.io/2017/03/30/red_black_binary_search_tree/">《Algorithms,4th Edition》读书笔记-红黑二叉查找树</a>.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/66/Red-black_tree_insert_case_5.png"></p>
<h4 id="情况5"><a href="#情况5" class="headerlink" title="情况5"></a>情况5</h4><p><code>P</code>为红色,<code>U</code>为黑色,且<code>N</code>为<code>P</code>的右子节点,我们需要先在<code>P</code>处进行一次<code>左旋转</code>,这样就又回到了情况4.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/5/56/Red-black_tree_insert_case_4.png"></p>
<h4 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fixAfterInsertion</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">while</span> (x != <span class="keyword">null</span> &amp;&amp; x != root &amp;&amp; colorOf(parentOf(x)) == RED) &#123;</span><br><span class="line">          <span class="keyword">if</span> (parentOf(x) == grandpaOf(x).left) &#123;</span><br><span class="line">              x = parentIsLeftNode(x);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              x = parentIsRightNode(x);</span><br><span class="line">          &#125;</span><br><span class="line">          fixSize(x);</span><br><span class="line">      &#125;</span><br><span class="line">      setColor(root, BLACK);</span><br><span class="line">  &#125;</span><br><span class="line">	</span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">parentIsLeftNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node xUncle = grandpaOf(x).right;</span><br><span class="line"><span class="comment">// 情况3</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(xUncle) == RED) &#123;</span><br><span class="line">          x = uncleColorIsRed(x, xUncle);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="comment">// 情况5</span></span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).right) &#123;</span><br><span class="line">              x = parentOf(x);</span><br><span class="line">              rotateLeft(x);</span><br><span class="line">          &#125;</span><br><span class="line">	<span class="comment">// 情况4</span></span><br><span class="line">          rotateRight(grandpaOf(x));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">parentIsRightNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node xUncle = grandpaOf(x).left;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (colorOf(xUncle) == RED) &#123;</span><br><span class="line">          x = uncleColorIsRed(x, xUncle);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).left) &#123;</span><br><span class="line">              x = parentOf(x);</span><br><span class="line">              rotateRight(x);</span><br><span class="line">          &#125;</span><br><span class="line">          rotateLeft(grandpaOf(x));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">uncleColorIsRed</span><span class="params">(Node x, Node xUncle)</span> </span>&#123;</span><br><span class="line">      setColor(parentOf(x), BLACK);</span><br><span class="line">      setColor(xUncle, BLACK);</span><br><span class="line">      setColor(grandpaOf(x), RED);</span><br><span class="line">      x = grandpaOf(x);</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;	</span><br></pre></td></tr></table></figure>
<h3 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h3><p>我们只考虑删除节点只有一个子节点的情况,且只有后继节点与删除节点都为黑色(如果删除节点为红色,从根节点到叶子节点的每条路径上少了一个红色节点并不会违反<code>红黑树</code>的性质,而如果后继节点为红色,只需要将它重新绘制为黑色即可).</p>
<p>先将删除节点替换为后继节点,且后继节点定义为<code>N</code>,它的兄弟节点为<code>S</code>.</p>
<h4 id="情况1-1"><a href="#情况1-1" class="headerlink" title="情况1"></a>情况1</h4><p><code>N</code>为新的根节点,在这种情况下只需要把根节点保持为黑色即可.</p>
<h4 id="情况2-1"><a href="#情况2-1" class="headerlink" title="情况2"></a>情况2</h4><p><strong><code>S</code>为红色,只需要在<code>P</code>进行一次<code>左旋转</code></strong>,接下来则<strong>继续按以下情况进行处理</strong>(尽管路径上的黑色节点数量没有改变,但<code>N</code>有了一个黑色的兄弟节点与红色的父节点).</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Red-black_tree_delete_case_2.png"></p>
<h4 id="情况3-1"><a href="#情况3-1" class="headerlink" title="情况3"></a>情况3</h4><p><code>S</code>和它的子节点都是黑色的,而<code>P</code>为红色.这种情况下只需要将<code>S</code>与<code>P</code>的颜色进行交换</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/d/d7/Red-black_tree_delete_case_4.png"></p>
<h4 id="情况4-1"><a href="#情况4-1" class="headerlink" title="情况4"></a>情况4</h4><p><strong><code>S</code>和它的子节点都是黑色的,这种情况下需要把<code>S</code>重新绘制为红色</strong>.这时不通过<code>N</code>的路径都将少一个黑色节点(通过<code>N</code>的路径因为删除节点是黑色的也都少了一个黑色节点),这让它们平衡了起来.</p>
<p>但现在通过<code>P</code>的路径比不通过<code>P</code>的路径都少了一个黑色节点,所以还需要在<code>P</code>上继续进行调整.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/c/c7/Red-black_tree_delete_case_3.png"></p>
<h4 id="情况5-1"><a href="#情况5-1" class="headerlink" title="情况5"></a>情况5</h4><p><strong><code>S</code>为黑色,它的左子节点为红色,右子节点为黑色.这种情况下,我们在<code>S</code>上做<code>右旋转</code></strong>,这样<code>S</code>的左儿子成为<code>S</code>的父亲和N的新兄弟。我们接着交换<code>S</code>和它的新父亲的颜色。所有路径仍有同样数目的黑色节点，但是现在<code>N</code>有了一个右儿子是红色的黑色兄弟，所以我们进入了情况6。<code>N</code>和<code>P</code>都不受这个变换的影响。</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/30/Red-black_tree_delete_case_5.png"></p>
<h4 id="情况6"><a href="#情况6" class="headerlink" title="情况6"></a>情况6</h4><p><strong><code>S</code>是黑色，它的右子节点是红色,我们在<code>N</code>的父亲<code>P</code>上做<code>左旋转</code></strong>.这样<code>S</code>成为<code>N</code>的父亲和<code>S</code>的右儿子的父亲。我们接着交换<code>N</code>的父亲和<code>S</code>的颜色，<strong>并使<code>S</code>的右儿子为黑色</strong>。子树在它的根上的仍是同样的颜色,但是,<code>N</code>现在增加了一个黑色祖先.所以,通过<code>N</code>的路径都增加了一个黑色节点.此时,如果一个路径不通过<code>N</code>,则有两种可能性:</p>
<ul>
<li>它通过<code>N</code>的新兄弟.那么它以前和现在都必定通过<code>S</code>和<code>N</code>的父亲,而它们只是交换了颜色.所以路径保持了同样数目的黑色节点.</li>
</ul>
<ul>
<li>它通过<code>N</code>的新叔父,<code>S</code>的右儿子.那么它以前通过<code>S</code>、<code>S</code>的父亲和<code>S</code>的右儿子,但是现在只通过<code>S</code>,它被假定为它以前的父亲的颜色,和<code>S</code>的右儿子,它被从红色改变为黑色.合成效果是这个路径通过了同样数目的黑色节点.</li>
</ul>
<p>在任何情况下,在这些路径上的黑色节点数目都没有改变.所以我们恢复了性质4.在示意图中的白色节点可以是红色或黑色,但是在变换前后都必须指定相同的颜色.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/3/31/Red-black_tree_delete_case_6.png"></p>
<h4 id="代码-1"><a href="#代码-1" class="headerlink" title="代码"></a>代码</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">fixAfterDeletion</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">while</span> (x != <span class="keyword">null</span> &amp;&amp; x != root &amp;&amp; colorOf(x) == BLACK) &#123;</span><br><span class="line">          <span class="keyword">if</span> (x == parentOf(x).left) &#123;</span><br><span class="line">              x = successorIsLeftNode(x);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              x = successorIsRightNode(x);</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      setColor(x, BLACK);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">successorIsLeftNode</span><span class="params">(Node x)</span> </span>&#123;</span><br><span class="line">      Node brother = parentOf(x).right;</span><br><span class="line"><span class="comment">// 情况2</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(brother) == RED) &#123;</span><br><span class="line">          rotateLeft(parentOf(x));</span><br><span class="line">          brother = parentOf(x).right;</span><br><span class="line">      &#125;</span><br><span class="line"><span class="comment">// 情况3,4</span></span><br><span class="line">      <span class="keyword">if</span> (colorOf(brother.left) == BLACK &amp;&amp; colorOf(brother.right) == BLACK) &#123;</span><br><span class="line">          x = brotherChildrenColorIsBlack(x, brother);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">	<span class="comment">// 情况5</span></span><br><span class="line">          <span class="keyword">if</span> (colorOf(brother.right) == BLACK) &#123;</span><br><span class="line">              rotateRight(brother);</span><br><span class="line">              brother = parentOf(x).right;</span><br><span class="line">          &#125;</span><br><span class="line">	<span class="comment">// 情况6</span></span><br><span class="line">          setColor(brother.right, BLACK);</span><br><span class="line">          rotateLeft(parentOf(x));</span><br><span class="line">          x = root;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">private</span> Node <span class="title">brotherChildrenColorIsBlack</span><span class="params">(Node x, Node brother)</span> </span>&#123;</span><br><span class="line">      setColor(brother, RED);</span><br><span class="line">      x = parentOf(x);</span><br><span class="line">      <span class="keyword">return</span> x;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h3 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h3><ul>
<li><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%BA%A2%E9%BB%91%E6%A0%91">Wikipedia</a></li>
</ul>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/14/2017-06-14-sort_algorithms_qucikSort/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/06/14/2017-06-14-sort_algorithms_qucikSort/" class="post-title-link" itemprop="url">深入浅出排序算法(3)-快速排序</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-14 16:30:00" itemprop="dateCreated datePublished" datetime="2017-06-14T16:30:00+08:00">2017-06-14</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">排序算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p><code>快速排序</code>与<code>归并排序</code>一样也是基于分治算法的排序算法.所以它的实现方法也与其他的分治算法一样,需要进行分解子任务,处理子任务,归并子任务这些步骤.</p>
<p>但<code>快速排序</code>与<code>归并排序</code>不同,它是一种<code>原地排序</code>算法(不需要额外的辅助数组),且<code>快速排序</code>不使用中间值来分解任务,而是使用<code>划分函数</code>.</p>
<h3 id="算法过程"><a href="#算法过程" class="headerlink" title="算法过程"></a>算法过程</h3><hr>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif"></p>
<ul>
<li>从数组中挑选出一个值,作为<code>基准值 k</code>.</li>
</ul>
<ul>
<li>重新排序序列,<strong>将所有小于<code>k</code>的值放到<code>k</code>前面,所有大于<code>k</code>的值放到<code>k</code>后面</strong>(也可以理解为将数组<code>a</code>切分为两个子数组<code>a[begin...k-1],a[k+1...end]</code>,其中前一个子数组都小于<code>k</code>,后一个子数组都大于<code>k</code>).</li>
</ul>
<ul>
<li>递归地将两个子数组进行快速排序(递归到最底部时,子数组的大小是零或一,也就是已经排序好了.).</li>
</ul>
<h3 id="划分函数"><a href="#划分函数" class="headerlink" title="划分函数"></a>划分函数</h3><hr>
<p><code>划分函数</code>就是上述步骤中的第二步,它将数组根据<code>基准值</code>进行重排序.根据<code>基准值</code>选择的位置不同,<code>划分函数</code>也有不同的实现方法,不过其根本思想都是将小于<code>基准值</code>的值放到前面,大于<code>基准值</code>的值放到后面.</p>
<h4 id="使用末尾元素作为基准值"><a href="#使用末尾元素作为基准值" class="headerlink" title="使用末尾元素作为基准值"></a>使用末尾元素作为基准值</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用末尾元素作为基准值来进行切分</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">partitionUseEnd</span><span class="params">(Comparable[] a, <span class="keyword">int</span> begin, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">    Comparable pivot = a[end]; <span class="comment">// 基准值,切分后的数组应满足左边都小于基准,右边都大于基准</span></span><br><span class="line">    <span class="keyword">int</span> i = begin - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = begin; j &lt; end; j++) &#123;</span><br><span class="line">        <span class="comment">// 如果j小于基准值则与i交换</span></span><br><span class="line">        <span class="keyword">if</span> (less(a[j], pivot)) &#123;</span><br><span class="line">            i++;</span><br><span class="line">            swap(a, i, j);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 将基准值交换到正确的位置上</span></span><br><span class="line">    <span class="keyword">int</span> pivotLocation = i + <span class="number">1</span>;</span><br><span class="line">    swap(a, pivotLocation, end);</span><br><span class="line">    <span class="keyword">return</span> pivotLocation;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="使用首元素作为基准值"><a href="#使用首元素作为基准值" class="headerlink" title="使用首元素作为基准值"></a>使用首元素作为基准值</h4><hr>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用首元素作为基准值来进行切分</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">partitionUseBegin</span><span class="params">(Comparable[] a, <span class="keyword">int</span> begin, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">    Comparable pivot = a[begin];</span><br><span class="line">    <span class="keyword">int</span> i = begin;</span><br><span class="line">    <span class="keyword">int</span> j = end + <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        <span class="comment">// 从左向右扫描,直到找出一个大于等于基准的值</span></span><br><span class="line">        <span class="keyword">while</span> (less(a[++i], pivot)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (i &gt;= end)</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 从右向左扫描,直到找出一个小于等于基准的值</span></span><br><span class="line">        <span class="keyword">while</span> (less(pivot, a[--j])) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &lt;= begin)</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果指针i与j发生碰撞则结束循环</span></span><br><span class="line">        <span class="keyword">if</span> (i &gt;= j)</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="comment">// 将左边大于小于基准的值与右边小于等于基准的值进行交换</span></span><br><span class="line">        swap(a, i, j);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 将基准值交换到正确的位置上</span></span><br><span class="line">    swap(a, begin, j);</span><br><span class="line">    <span class="keyword">return</span> j;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><hr>
<p>了解了<code>划分函数</code>的实现,剩下就只需要递归地调用<code>快速排序</code>不断地分解子任务即可.</p>
<p>注意,<code>快速排序</code>与<code>归并排序</code>不同,它不需要进行<code>归并</code>(划分后就已经是有序的了),并且是先进行<code>划分函数</code>,再分解任务.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(Comparable[] a)</span> </span>&#123;</span><br><span class="line">    sort(a, <span class="number">0</span>, a.length - <span class="number">1</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(Comparable[] a, <span class="keyword">int</span> begin, <span class="keyword">int</span> end)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (begin &gt;= end)</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> k = partitionUseEnd(a, begin, end);</span><br><span class="line">    sort(a, begin, k - <span class="number">1</span>);</span><br><span class="line">    sort(a, k + <span class="number">1</span>, end);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun/">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2017/06/12/2017-06-12-sort_algorithmes_mergeSort/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/yuwanzi.io/2017/06/12/2017-06-12-sort_algorithmes_mergeSort/" class="post-title-link" itemprop="url">深入浅出排序算法(2)-归并排序</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2017-06-12 15:00:00" itemprop="dateCreated datePublished" datetime="2017-06-12T15:00:00+08:00">2017-06-12</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/" itemprop="url" rel="index"><span itemprop="name">Algorithms</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/Algorithms/%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">排序算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><hr>
<p><code>归并排序</code>是基于分治算法实现的一种排序算法,它将数组分割为两个子数组,然后对子数组进行排序,最终将子数组<code>归并</code>为有序的数组.</p>
<p><code>归并排序</code>的时间复杂度为<code>O(n log n)</code>,空间复杂度为<code>O(1)</code>,并且它是稳定的排序算法(所谓稳定即是不影响值相等元素的相对次序).</p>
<h3 id="算法过程"><a href="#算法过程" class="headerlink" title="算法过程"></a>算法过程</h3><hr>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif"></p>
<ul>
<li>首先,<code>归并排序</code>需要将一个大小为<code>n</code>个元素的数组分解为各包含<code>n/2</code>个元素的子数组(这个分解的过程会不断进行,直到子数组元素个数为<code>1</code>).</li>
</ul>
<ul>
<li>当子数组的元素个数为<code>1</code>时,代表这个子数组已经有序,开始两两归并(将两个个数为<code>1</code>的子数组归并为一个个数为<code>2</code>的子数组,不断归并,直到所有子数组个数为<code>2</code>,然后继续将两个个数为<code>2</code>的子数组归并为一个个数为<code>4</code>的子数组….以此类推).</li>
</ul>
<ul>
<li>不断重复步骤2,直到整个数组有序.</li>
</ul>
<h3 id="归并"><a href="#归并" class="headerlink" title="归并"></a>归并</h3><hr>
<p>通过以上的了解,我们发现<code>归并排序</code>中最重要的步骤就是<code>归并</code>.</p>
<p>采用类似<code>洗牌</code>的方式来理解这个过程.想象辅助数组为一个空牌堆,两个子数组为两堆牌<code>a</code>和<code>b</code>.我们从<code>a</code>堆与<code>b</code>堆中<strong>各取出一张牌进行比较,然后将较小的牌放入空牌堆中</strong>,不断重复比较直到任一牌堆为空.最后,再将未空的牌堆全部放入空牌堆中.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 将两个子序列进行归并</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">merge</span><span class="params">(Comparable[] a, <span class="keyword">int</span> lo, <span class="keyword">int</span> mid, <span class="keyword">int</span> hi)</span> </span>&#123;</span><br><span class="line">    Comparable[] aux = <span class="keyword">new</span> Comparable[a.length]; <span class="comment">// 辅助数组</span></span><br><span class="line">    <span class="keyword">int</span> i = lo, j = mid + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> count = lo;</span><br><span class="line">    <span class="comment">// 对[lo...mid] 与 [mid+1...hi] 两个子序列的首元素进行比较,将较小的元素放入辅助数组</span></span><br><span class="line">    <span class="keyword">while</span> (i &lt;= mid &amp;&amp; j &lt;= hi) &#123;</span><br><span class="line">        <span class="keyword">if</span> (less(a[i], a[j]))</span><br><span class="line">            aux[count++] = a[i++];</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            aux[count++] = a[j++];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将[lo...mid] 与 [mid+1...hi] 两个子序列中剩余的元素放入辅助数组</span></span><br><span class="line">    <span class="keyword">while</span> (i &lt;= mid) &#123;</span><br><span class="line">        aux[count++] = a[i++];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span> (j &lt;= hi) &#123;</span><br><span class="line">        aux[count++] = a[j++];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 将辅助数组中的元素复制到源数组中</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> k = lo; k &lt;= hi; k++) &#123;</span><br><span class="line">        a[k] = aux[k];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="递归实现"><a href="#递归实现" class="headerlink" title="递归实现"></a>递归实现</h3><hr>
<p>只要理解了<code>归并</code>的过程,剩下就很容易实现了.<code>归并排序</code>的递归实现如下.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(Comparable[] a)</span> </span>&#123;</span><br><span class="line">      sort(a, <span class="number">0</span>, a.length - <span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">	</span><br><span class="line">  <span class="comment">// 递归实现归并排序</span></span><br><span class="line">  <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sort</span><span class="params">(Comparable[] a, <span class="keyword">int</span> lo, <span class="keyword">int</span> hi)</span> </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (lo &gt;= hi)</span><br><span class="line">          <span class="keyword">return</span>;</span><br><span class="line"></span><br><span class="line">      <span class="keyword">int</span> mid = (lo + hi) &gt;&gt;&gt; <span class="number">1</span>; <span class="comment">// (lo + hi) / 2</span></span><br><span class="line"><span class="comment">// 分解数组</span></span><br><span class="line">      sort(a, lo, mid);</span><br><span class="line">      sort(a, mid + <span class="number">1</span>, hi);</span><br><span class="line"><span class="comment">// 归并</span></span><br><span class="line">      merge(a, lo, mid, hi);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<h3 id="非递归实现"><a href="#非递归实现" class="headerlink" title="非递归实现"></a>非递归实现</h3><hr>
<p>我们已经知道了<code>归并排序</code>中最小子数组的元素个数为<code>1</code>,非递归实现只需要从<code>1</code>开始自底向上地归并即可(递归实现的真实计算过程也是如此,这是由于递归调用是后进先出的).</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">   <span class="comment">// 非递归实现归并排序</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">sortUnRecursive</span><span class="params">(Comparable[] a)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">int</span> len = <span class="number">1</span>; <span class="comment">// 自底向上实现归并排序,子序列的最小粒度为1</span></span><br><span class="line">       <span class="keyword">while</span> (len &lt; a.length) &#123;</span><br><span class="line">           <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; a.length; i += len &lt;&lt; <span class="number">1</span>) &#123;</span><br><span class="line">               merge(a, i, len);</span><br><span class="line">           &#125;</span><br><span class="line">           len = len &lt;&lt; <span class="number">1</span>; <span class="comment">// 子序列规模每次迭代时乘2</span></span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 与递归实现的归并函数不同,需要注意边界检查</span></span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">merge</span><span class="params">(Comparable[] a, <span class="keyword">int</span> lo, <span class="keyword">int</span> hi)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">int</span> length = a.length;</span><br><span class="line">       Comparable[] aux = <span class="keyword">new</span> Comparable[length];</span><br><span class="line">       <span class="keyword">int</span> count = lo;</span><br><span class="line">       <span class="comment">// 子数组1</span></span><br><span class="line">       <span class="keyword">int</span> i = lo;</span><br><span class="line">       <span class="keyword">int</span> i_bound = lo + hi;</span><br><span class="line">       <span class="comment">// 子数组2</span></span><br><span class="line">       <span class="keyword">int</span> j = i_bound;</span><br><span class="line">       <span class="keyword">int</span> j_bound = j + hi;</span><br><span class="line"></span><br><span class="line">       <span class="comment">// 注意j的边界检查</span></span><br><span class="line">       <span class="keyword">while</span> (i &lt; i_bound &amp;&amp; j &lt; j_bound &amp;&amp; j &lt; length) &#123;</span><br><span class="line">           <span class="keyword">if</span> (less(a[i], a[j]))</span><br><span class="line">               aux[count++] = a[i++];</span><br><span class="line">           <span class="keyword">else</span></span><br><span class="line">               aux[count++] = a[j++];</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="comment">// i和j都有可能越界</span></span><br><span class="line">       <span class="keyword">while</span> (i &lt; i_bound &amp;&amp; i &lt; length) &#123;</span><br><span class="line">           aux[count++] = a[i++];</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">while</span> (j &lt; j_bound &amp;&amp; j &lt; length) &#123;</span><br><span class="line">           aux[count++] = a[j++];</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">int</span> k = lo;</span><br><span class="line">       <span class="keyword">while</span> (k &lt; j &amp;&amp; k &lt; length) &#123;</span><br><span class="line">           a[k] = aux[k];</span><br><span class="line">           k++;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;	</span><br></pre></td></tr></table></figure>
<blockquote>
<p>本文作者为<a target="_blank" rel="noopener" href="https://github.com/SylvanasSun">SylvanasSun(sylvanassun_xtz@163.com)</a>,转载请务必指明原文链接.</p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/yuwanzi.io/page/2/"><i class="fa fa-angle-left" aria-label="Vorherige Seite"></i></a><a class="page-number" href="/yuwanzi.io/">1</a><a class="page-number" href="/yuwanzi.io/page/2/">2</a><span class="page-number current">3</span><a class="page-number" href="/yuwanzi.io/page/4/">4</a><span class="space">&hellip;</span><a class="page-number" href="/yuwanzi.io/page/7/">7</a><a class="extend next" rel="next" href="/yuwanzi.io/page/4/"><i class="fa fa-angle-right" aria-label="Nächste Seite"></i></a>
  </nav>


<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
